我是Nginx的新手,正在尝试将WordPress网站的以下规则从Apache转换为Nginx。我从运行Nginx1.4.6的Ubuntu机器上的默认Nginx配置开始。
RewriteCond %{REQUEST_URI} !^/wp-content/themes/path/to/exclude/file'.php
RewriteRule wp-content/themes/(.*'.php)$ log.php?f=$1 [L]
上述规则将所有请求重写为wp-content/themes/*.php
到security-log.php
,RewriteCond
规则中定义的文件除外。
据我所知,在Nginx中实现这一点的方法是使用location
块。我已经尝试了以下操作(我仍然不确定如何排除特定的文件/文件夹)。
location = /wp-content/plugins/(.*'.php)$ {
try_files /security-log.php =404;
}
上面的规则似乎被完全忽略了(也许我的正则表达式有问题?)。
如果我提供一个固定的路径,如下所示,则会调用规则,但Nginx将为PHP文件提供服务(浏览器将下载该文件),而不是使用PHP解释器执行它(很可能这是因为fast-cgi
没有被调用)。
location = /wp-content/plugins/test.php {
try_files /security-log.php =404;
}
实现这一目标的最佳方式是什么?
您的第一次尝试对于正则表达式位置是无效语法。它可能应该是这样的:
location ~ ^/wp-content/plugins/.*'.php$ { ... }
与其使用try_files
指令,不如使用rewrite
,如下所示:
rewrite ^ /security-log.php last;
当然,这两种方法都与.htaccess
文件的功能不匹配。
您已经注意到,处理PHP文件的位置块必须包含fastcgi
指令。这可以通过将它们放在一个单独的文件中并使用include
指令将它们拉入多个location
块来实现。
这意味着.htaccess
文件可以通过在现有location ~ '.php$
块之前放置regex位置来实现。例如:
location = /wp-content/themes/path/to/exclude/file.php {
include common-php-directives;
}
location ~ ^/wp-content/themes/.*'.php$ {
rewrite ^/wp-content/themes/(.*'.php)$ /log.php?f=$1 last;
}
location ~ '.php$ {
include common-php-directives;
}
有关位置语法,请参阅本文档。
我可以建议你作为nginx的新用户阅读这个陷阱文档https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
对于wordpress设置:https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/