问题描述
我正在尝试创建一个 Nginx 配置,它对以 /craft
开头的所有路由使用 PHP-FPM,并为所有其他路由使用另一个代理(应该为 Next.js 应用程序提供服务):
# Next.js upstream config
upstream nextjs {
server host.docker.internal:3000;
}
# Proxy cache
proxy_cache_path /var/cache/Nginx levels=1:2 keys_zone=STATIC:10m inactive=7d use_temp_path=off;
server {
listen 80;
listen [::]:80;
server_name localhost;
# Document root
root /var/www/html/web;
index index.PHP;
# Logs
access_log /var/log/Nginx/access.log main;
error_log /var/log/Nginx/error.log warn;
# Craft CMS
location /craft {
include "/etc/Nginx/sites-shared/static-files.conf";
try_files $uri $uri/ /index.PHP?$query_string;
}
location ~ [^/]\.PHP(/|$) {
try_files $uri $uri/ /index.PHP?$query_string;
fastcgi_split_path_info ^(.+\.PHP)(/.+)$;
fastcgi_pass unix:/var/run/PHP-fpm/www.sock;
fastcgi_index index.PHP;
include fastcgi_params;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
}
# Next.js's built assets
# browser cache - max cache headers from Next.js as build id in url
# Server cache - valid forever (cleared after cache "inactive" period)
location /_next/static {
proxy_cache STATIC;
proxy_pass http://nextjs;
}
# Next.js's static assets
# browser cache - "no-cache" headers from Next.js as no build id in url
# Server cache - refresh regularly in case of changes
location /static {
proxy_cache STATIC;
proxy_ignore_headers Cache-Control;
proxy_cache_valid 60m;
proxy_pass http://nextjs;
}
# Next.js app
location / {
proxy_pass http://nextjs;
}
}
安装有效(在 https://foobar.dev:8843/craft/index.php?p=admin/install 上运行),但是一旦我被重定向到 https://foobar.dev:8843/craft/admin/dashboard,我就会收到以下错误:
2021/02/11 11:39:03 [error] 32#32: *1 rewrite or internal redirection cycle while internally redirecting to "/index.PHP",client: 172.20.0.1,server: localhost,request: "GET /craft/admin/dashboard HTTP/2.0",host: "foobar.dev:8843",referrer: "https://foobar.dev:8843/craft/index.PHP?p=admin/install"
这是我的 /var/www/html
目录结构:
.
└── /
├── config
├── modules
├── storage
├── templates
├── vendor
├── web/
│ ├── app/
│ │ └── index.PHP
│ └── craft/
│ ├── cpresources
│ └── index.PHP
├── .env
├── composer.json
├── composer.lock
└── craft
https://foobar.dev:8843/app/
也能正常工作,但 URL 的重写似乎不起作用,我不明白错误消息中提到的重定向循环。
解决方法
使用此配置可以正常工作:
# Craft CMS
location /craft {
try_files $uri $uri/ /craft/index.php?$query_string;
}
location ~ [^/]\.php(/|$) {
# 404
try_files $fastcgi_script_name =404;
# default fastcgi_params
include fastcgi_params;
# fastcgi settings
fastcgi_pass unix:/var/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
# fastcgi params
fastcgi_param DOCUMENT_ROOT $realpath_root;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
}