我的 Nginx 配置抛出 404.php
如下:
## Any other attempt to access PHP files returns a 404.
location ~* ^.+\.php$ {
return 404;
}
Run Code Online (Sandbox Code Playgroud)
但是,我要运行的子文件夹中有一些 index.php 文件。当前的配置是这样的:
location = /sitename/subpage/index.php {
fastcgi_pass phpcgi; #where phpcgi is defined to serve the php files
}
location = /sitename/subpage2/index.php {
fastcgi_pass phpcgi;
}
location = /sitename/subpage3/index.php {
fastcgi_pass phpcgi;
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但问题是重复的位置,如果有很多子页面,那么配置就会变得很大。
我尝试了像 * 和一些正则表达式这样的通配符,它表示 nginx 测试通过但没有加载页面,即 404。我尝试的是:
location = /sitename/*/index.php {
fastcgi_pass phpcgi;
}
location ~* ^/sitename/[a-z]/index.php$ {
fastcgi_pass phpcgi;
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以在该位置使用一些路径名作为正则表达式或通配符?
Ter*_*nen 34
块中的=
修饰符location
是完全匹配,没有任何通配符、前缀匹配或正则表达式。这就是它不起作用的原因。
在您的正则表达式尝试中,[a-z]
匹配a
和之间的单个字符z
。这就是为什么它对你不起作用。
您需要按如下方式设置您的位置。注意location
语句的顺序。nginx 选择第一个匹配的正则表达式条件。
location ~ ^/sitename/[0-9a-z]+/index.php$ {
fastcgi_pass phpcgi;
}
location ~ \.php$ {
return 404;
}
Run Code Online (Sandbox Code Playgroud)
我在这里使用区分大小写的匹配(~
修饰符而不是~*
)。在第一种情况下,我匹配路径的第一部分,然后匹配一个或多个字母/数字字符,然后匹配index.php
. 您可以修改匹配范围,但请记住+
“一次或多次”重复。
第二个匹配任何以 结尾的 URI .php
。由于正则表达式的工作方式,您的版本中不需要额外的字符。