我正在寻找一种使用 php 应用程序配置 nginx 的方法。
如果存在静态文件,它应该提供这些文件。如果它们位于子文件夹 /dev 中,则仅允许它们用于 127.0.0.1;
非静态文件的 uri 应通过第三个位置块重定向到 php。
如果这个到 php 的 uri 以 /dev 开头,我希望重写 uri 时不带 /dev,并将 fastcgi_param APP_ENV 设置为“dev”。 (并且除了 127.0.0.1 之外的任何 uri 都被阻止)
如果这个 uri 不是以 /dev 开头,我只想将 fastcgi_param APP_ENV 设置为“prod”,而无需重写。
server {
root /var/www/homeserver/public;
location /dev {
allow 127.0.0.1;
deny all;
# This has no effect on the third location block:
fastcgi_param APP_ENV dev;
# This is only OK for when try_files pass the uri to /index.php
rewrite ^/dev(.*)$ /$1 last;
try_files $uri /index.php$is_args$args;
}
location / {
# This has no effect on the third location block:
fastcgi_param APP_ENV prod;
try_files $uri /index.php$is_args$args;
}
# Front controler :
location ~ ^/index\.php(/|$) {
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
internal;
}
location ~ \.php$ {
return 404;
}
}
我尝试使用“if”语句来解决这个问题。但没有成功。
我该如何配置它?
答案1
尝试这个配置(我没有测试过,但我希望它能满足你的要求)。
server {
root /var/www/homeserver/public;
location /dev {
allow 127.0.0.1;
deny all;
rewrite ^/dev/(.*)$ /$1 break;
try_files $uri $uri/ /index.php$is_args$args;
location ~* [^/]\.php(/|$) {
gzip off;
expires off; ## Do not cache dynamic content
fastcgi_intercept_errors on;
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404 "Error 404 Not found. (err#002)";
}
include fastcgi_params;
fastcgi_param APP_ENV dev;
fastcgi_index index.php;
fastcgi_param HTTP_PROXY ""; # Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param SCRIPT_FILENAME $request_filename;
# fastcgi_param DOCUMENT_ROOT $realpath_root; # DOCUMENT_ROOT already specified in fastcgi_params
}
}
location / {
try_files $uri $uri/ /index.php$is_args$args;
location ~* [^/]\.php(/|$) {
gzip off;
expires off; ## Do not cache dynamic content
fastcgi_intercept_errors on;
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404 "Error 404 Not found. (err#001)";
}
include fastcgi_params;
fastcgi_param APP_ENV prod;
fastcgi_index index.php;
fastcgi_param HTTP_PROXY ""; # Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param SCRIPT_FILENAME $request_filename;
# fastcgi_param DOCUMENT_ROOT $realpath_root; # DOCUMENT_ROOT already specified in fastcgi_params
}
}
}