我的主网站上安装了 WordPress,并运行 nginx/1.18.0,但我还有一个单独的目录“services”,其中包含我只想在无扩展版本中提供的 PHP 文件,并且还添加了一个尾随斜杠。
到目前为止,我已经成功提供无扩展名的 PHP 文件,但如果您导航到 PHP 版本,该版本仍然可用,并且没有添加尾随斜杠。
下面是我的完整配置。
server {
server_name example.com www.example.com;
access_log /var/www/example.com/logs/access.log;
error_log /var/www/example.com/logs/error.log;
rewrite_log on;
root /var/www/example.com/public/;
index index.php;
location /services {
try_files $uri $uri.html $uri/ @extensionless-php;
rewrite ^(/.*)\.php(\?.*)?$ $1$2 permanent;
rewrite ^/(.*)/$ /$1 permanent;
}
location @extensionless-php {
rewrite ^(.*)$ $1.php last;
return 301 $uri/;
}
location / {
try_files $uri $uri/ /index.php?$args;
}
# FastCGI
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.3-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS on;
fastcgi_param HTTP_SCHEME https;
fastcgi_read_timeout 150;
}
}
我阅读了以下三篇文章才得出这个配置:
错误日志中也没有任何错误或通知,所以我确定我是不是把规则搞混了。我该如何纠正?
答案1
尝试这个来代替location /services { ... }
和location @extensionless-php { ... }
:
...
root /var/www/example.com/public; # remove the trailing slash!
index index.php;
location ^~ /services/ {
# redirect '/services/some/path.php' to '/services/some/path/'
location ~ \.php$ {
rewrite ^(.*)\.php$ $1/ permanent;
}
# process the '/services/some/path' request (without the trailing slash)
# this request cannot end with 'php' (that requests captured earlier),
# but it can be a request for some existing assets file (.js, .css, image etc.)
location ~ [^/]$ {
# if '/services/some/path' isn't an existing file,
# redirect the request to '/services/some/path/'
if (!-f $document_root$uri) {
rewrite ^ $uri/ permanent;
}
}
# process the '/services/some/path/' request
location ~ ^(.*)/$ {
# try '/services/some/path.php' file
set $script $document_root$1.php;
# but if the '/services/some/path' is a directory,
# try '/services/some/path/index.php' file instead
if (-d $document_root$1) {
set $script $document_root$1/index.php;
}
# return 404 if the file does not exists
if (!-f $script) {
return 404;
}
# handle the file with the PHP-FPM
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $script;
# most likely these two doesn't needed for '/services/'
# (needed for WordPress only) and can be safely removed
fastcgi_param HTTPS on;
fastcgi_param HTTP_SCHEME https;
fastcgi_read_timeout 150;
fastcgi_pass unix:/run/php/php7.3-fpm.sock;
}
}
...
是的,它看起来有点复杂,就像您的要求一样。请注意,您需要一个单独的 PHP 处理程序,这是因为您不想提供 URI,/.../file.php
而是重定向它们。
保持其他两个位置(为 WordPress 提供服务)不变。