location配置
Location 匹配规则
# 精确匹配(优先级最高) location = /exact { # 只匹配 /exact } # 正则匹配(区分大小写) location ~ \.php$ { # 匹配以.php结尾的请求 } # 正则匹配(不区分大小写) location ~* \.(jpg|jpeg|png|gif)$ { # 匹配图片文件 } # 前缀匹配(优先级高于正则) location ^~ /static/ { # 匹配以/static/开头的请求 } # 普通前缀匹配 location /api/ { # 匹配以/api/开头的请求 } # 通用匹配(最低优先级) location / { # 匹配所有请求 }
静态文件服务
location / { 匹配 所有请求 root /var/www/html; 配置站点的 根目录 index index.html; 默认首页文件 try_files $uri $uri/ =404; 如果请求 /foo,Nginx 会按顺序查找 /foo 或 /foo/(看它是否为目录)。找不到时返回 404 错误。 } # 静态资源缓存 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { 正则匹配 expires 30d; 为匹配到的静态资源设置 缓存时间为 30 天 add_header Cache-Control "public, immutable"; 设置 Cache-Control 头,告诉浏览器: public:资源可以被任何缓存(包括浏览器、CDN、代理)缓存。 immutable:资源是不可变的 }
反向代理配置
location /api/ { 匹配所有以 /api/ 开头的请求 proxy_pass http://backend_server; 把匹配到的请求转发到 http://backend_server proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; 设置真实客户端的 IP 地址 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 如果请求通过了两个代理 A 和 B,它的 X-Forwarded-For 可能是 client_ip, A_ip, B_ip proxy_set_header X-Forwarded-Proto $scheme; 设置 请求的协议类型即请求是通过 http 还是 https 发出的 # 超时设置 proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; }
PHP-FPM 配置
location ~ \.php$ { 匹配所有以 .php 结尾的请求 root /var/www/html; fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_pass 用于指定 FastCGI 服务器,是指通过 Unix socket 与 PHP-FPM 进行通信 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 告诉 PHP-FPM 你要处理的文件的完整路径 include fastcgi_params; 加载 FastCGI 配置文件 }

浙公网安备 33010602011771号