我有两个应用程序:HTML + JS前端和PHP后端。 我想设置Nginx,以便两者都从同一个域中提供。 对后端的请求使用以/api开头的URL。
我的尝试是这样的:
server { root /path/to/frontend; index index.html; server_name example.com; location / { try_files $uri $uri/ /index.html; } location /api { alias /path/to/backend; index index.php; try_files $uri $uri/ /index.php; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } }
但是,对于后端的所有请求,我最终得到一个404:主脚本未知。
有没有办法实现我在这里要做的事情? 怎么样?
人们通常犯的错误并不是真正理解nginx是如何工作的。 请记住以下几点:
nginx总是只提供一个location块的请求 。
我build议你(重新)阅读以下内容: nginx如何处理请求
现在,看看你的configuration,后端请求将需要由2个位置服务:
location /api location ~\.php$ 在location文档之后,第一个被称为前缀位置,而第二个是正则expression式 (正则expression式)。 nginx将检查两个,但最终只会select一个,在你的情况是正则expression式之一。
现在,在处理它的时候,nginx会将/path/to/frontend/<yourFile>.php的请求转发给PHP,因为它是唯一定义的,所以从root /path/to/frontend构buildpath。 后端然后失败,无法find指定的文件。
您可能希望尝试以下操作:
location /api { alias /path/to/backend; index index.php; try_files $uri $uri/ /index.php; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; # Useless? Request always ending up with '.php' here... fastcgi_index index.php; include fastcgi_params; # Try to secure this block, which might lead to arbitrary code execution. } }
至于缺乏安全性,我在2014年10月底的nginx.conf上主持了关于nginx和PHP-FPM的讨论。 幻灯片可用: https : //rosset.net/LAMP_just_died.pptx 。 video很快可用。