1. 基本配置
首先,我们需要编辑 Nginx 的主配置文件 nginx.conf
。这个文件通常位于 /etc/nginx/nginx.conf
或 /usr/local/nginx/conf/nginx.conf
。
示例:基本配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
# Gzip Settings
gzip on;
gzip_disable "msie6";
# Include other configuration files
include /etc/nginx/conf.d/*.conf;
}
2. 配置虚拟主机
虚拟主机允许您在同一台服务器上托管多个网站。每个虚拟主机的配置通常放在 /etc/nginx/conf.d/
目录下的单独文件中。
示例:虚拟主机配置
创建一个文件 /etc/nginx/conf.d/example.com.conf
:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# Logs
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}
3. 反向代理
Nginx 可以用作反向代理,将请求转发到后端服务器。
示例:反向代理配置
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
4. 负载均衡
Nginx 可以配置为负载均衡器,将请求分发到多个后端服务器。
示例:负载均衡配置
http {
upstream backend_servers {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
server {
listen 80;
server_name loadbalancer.example.com;
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
5. 静态内容服务
Nginx 可以高效地提供静态内容,如图片、CSS 和 JavaScript 文件。
示例:静态内容服务配置
server {
listen 80;
server_name static.example.com;
root /var/www/static.example.com;
location / {
try_files $uri $uri/ =404;
}
location ~* \.(jpg|jpeg|png|gif|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
}
6. 测试和重新加载配置
在修改配置文件后,建议先测试配置文件是否正确:
sudo nginx -t
如果测试通过,可以重新加载 Nginx 以应用新的配置:
sudo systemctl reload nginx
或者
sudo service nginx reload
以上是一些常见的 Nginx 配置示例。根据您的具体需求,您可以进一步调整和优化这些配置。
标签:基本,log,nginx,配置,server,Nginx,proxy,com,example From: https://www.cnblogs.com/wyl-1113/p/18527493