Nginx配置子目录映射WordPress站点报错求助
场景说明
文件结构:
/var/www/example.com- Laravel站点目录/var/www/cms- WordPress博客目录
需求:通过https://example.com/blogs/访问WordPress博客,当前配置出现两类问题,以下是针对性解决方案。
问题1:目录索引禁止错误
错误日志
[error] 1193696#1193696: *69 directory index of "/var/www/cms" is forbidden, client: 89.69.169.171, server: example.com, request: "GET /blogs/ HTTP/2.0", host: "example.com"
原因
原location ^~ /blogs/中的try_files最后一项/index.php指向的是Laravel站点的入口文件,而非WordPress的/var/www/cms/index.php;同时alias与location的路径拼接逻辑不匹配,导致Nginx无法正确找到WordPress的索引文件。
修正方案
调整/blogs/的location配置,确保请求正确转发到WordPress入口:
location ^~ /blogs/ { alias /var/www/cms/; # 保留尾斜杠,与location路径匹配,避免拼接错误 index index.php; # 修正try_files,指向WordPress入口并携带请求参数 try_files $uri $uri/ /blogs/index.php?$args; location ~ [^/]\.ph(p\d*|tml)$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; include snippets/fastcgi-php.conf; # 关键:覆盖SCRIPT_FILENAME,适配alias路径解析逻辑 fastcgi_param SCRIPT_FILENAME $request_filename; } }
问题2:FastCGI响应缓冲到临时文件警告
警告日志
[warn] 1192265#1192265: *92 an upstream response is buffered to a temporary file /var/lib/nginx/fastcgi/1/00/0000000001 while reading upstream, client: 89.69.169.171, server: example.com, request: "GET /_debugbar/assets/javascript/?v=1695127990 HTTP/2.0", upstream: "fastcgi://unix:/var/run/php/php8.2-fpm.sock:", host: "example.com", referrer: "https://example.com/blogs/"
原因
Nginx默认的FastCGI缓冲区过小,导致部分响应内容无法直接内存缓存,被迫写入临时文件。
修正方案
在@php location中添加缓冲区参数,提升缓存容量:
location @php { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 调整缓冲区参数,避免写入临时文件 fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_temp_file_write_size 64k; }
完整修正后的Nginx配置
server { server_name example.com; charset UTF-8; index index.php; root /var/www/example.com/public; include /etc/nginx/vhosts-includes/*.conf; location ^~ /blogs/ { alias /var/www/cms/; index index.php; try_files $uri $uri/ /blogs/index.php?$args; location ~ [^/]\.ph(p\d*|tml)$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; include snippets/fastcgi-php.conf; fastcgi_param SCRIPT_FILENAME $request_filename; } } location / { if ($http_host !~ "^example.com") { return 301 $scheme://example.com$request_uri; } try_files $uri $uri/ /index.php?_url=$uri&$args; location ~ [^/]\.ph(p\d*|tml)$ { try_files /does_not_exists @php; } } location @php { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_temp_file_write_size 64k; } location @fallback { } ssi on; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH; ssl_prefer_server_ciphers on; ssl_protocols TLSv1.2 TLSv1.3; # 移除过时协议,提升安全性 listen 443 ssl http2; }
额外提示:修改配置后,执行nginx -t验证配置正确性,再执行systemctl reload nginx生效。
内容的提问来源于stack exchange,提问作者Aleksandr Mendel

