Nginx是一款高性能的HTTP和反向代理服务器,下面我将详细介绍如何配置Nginx作为Web服务器。
sudo apt update
sudo apt install nginx
sudo yum install epel-release
sudo yum install nginx
Nginx的主要配置文件位于:
- 主配置文件:/etc/nginx/nginx.conf
- 站点配置文件:/etc/nginx/conf.d/
或 /etc/nginx/sites-available/
创建一个新的配置文件(例如/etc/nginx/conf.d/mysite.conf
):
server {
listen 80;
server_name example.com www.example.com;
root /var/www/mysite;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 静态文件缓存设置
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
# 错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
listen 80; # IPv4
listen [::]:80; # IPv6
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm index.php;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# 重定向www到非www
server {
listen 80;
server_name www.example.com;
return 301 http://example.com$request_uri;
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
首先确保你已经获取了SSL证书,然后配置:
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# SSL优化配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
root /var/www/html;
index index.html;
# 其他配置...
}
location /api/ {
proxy_pass http://localhost:3000/;
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;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
测试配置语法:
sudo nginx -t
重载配置(不中断服务):
sudo systemctl reload nginx
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl status nginx
在/etc/nginx/nginx.conf
中进行全局优化:
worker_processes auto; # 自动设置工作进程数为CPU核心数
worker_connections 1024; # 每个工作进程的最大连接数
# 启用gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
通过以上配置,你就可以搭建一个功能完善的Nginx Web服务器了。根据你的具体需求,可以进一步调整和优化这些配置。