我通过一个index.php文件路由所有的东西。我不想让任何人直接访问我的/var/www/html目录中的php文件,除了index.php。
我有这个来禁用对php文件的访问:
location ~ /*.php {
return 404;
}
但不幸的是,我的index.php文件仍然得到了404。
我使用以下代码通过index.php路由所有内容:
location / {
try_files $uri $uri/ /index.php?$args;
}
我怎样才能让这两者同时工作呢?
发布于 2021-10-26 04:53:28
在您的配置中,对于任何包含php
子字符串的请求,都没有找到HTTP404:
'/*' + '.' + 'php'
| | |
| | +--- 'php' substring
| +---------- any single char
+----------------- 0 or more '/' chars
我不认为这真的是你写的那个意思。匹配任何以.php
结尾的正则表达式模式的正确正则表达式模式是\.php$
模式。有关其他信息,请检查PCRE正则表达式模式语法。
要匹配除index.php
之外的所有PHP文件,您可以使用精确匹配位置(它优先于正则表达式匹配位置):
location / {
try_files $uri $uri/ /index.php?$args;
}
location = /index.php {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_pass <your_PHP-FPM_backend>;
}
location ~ \.php$ { # will be used for any PHP request except 'index.php'
return 404;
}
使用^~
位置修饰符可以实现相同的效果。如果最长匹配前缀位置具有^~
修饰符,则不检查正则表达式:
location / {
try_files $uri $uri/ /index.php?$args;
}
location ^~ /index.php {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_pass <your_PHP-FPM_backend>;
}
location ~ \.php$ { # will be used for any PHP request except 'index.php'
return 404;
}
如果您在不同的目录中有多个index.php
文件,则以前的解决方案将不起作用,您需要使用两个正则表达式匹配位置:
location / {
index index.php;
try_files $uri $uri/ /index.php?$args;
}
location ~ /index\.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass <your_PHP-FPM_backend>;
}
location ~ \.php$ { # will be used for any PHP request except 'index.php'
return 404;
}
这是唯一一个位置块顺序很重要的配置。location ~ /index\.php$ { ... }
应该是第一个,否则任何PHP文件请求都将被location ~ \.php$ { ... }
文件阻塞。
有关更多信息,请查看location
指令description和How nginx processes a request文档页面。您还可以查看Nginx redirect all traffic to index.php, but don't allow arbitrary file access SO thread,以获得其他一些示例。
https://stackoverflow.com/questions/69717335
复制相似问题