如何在Nginx中去除.php与.html扩展名并使.php文件返回404
在Nginx中移除.php/.html扩展名并隐藏原文件访问
要实现你需要的效果,核心分三步处理:重定向带扩展名的外部请求到无扩展名URL、内部映射无扩展名请求到对应文件、禁止外部直接访问带扩展名的文件。以下是完整的Nginx配置方案:
1. 配置重定向(带扩展名→无扩展名)
在server块中添加rewrite规则,将所有带.php或.html的请求永久重定向到无扩展名版本(301重定向对SEO友好):
# 重定向.php和.html请求到无扩展名URL rewrite ^/(.*)\.(php|html)$ /$1 permanent;
这条规则会匹配https://example.com/example.php,重定向到https://example.com/example;同理处理.html后缀的请求。
2. 内部映射无扩展名请求到对应文件
通过try_files指令,让Nginx在处理无扩展名请求时,自动尝试匹配对应的.php或.html文件:
location / { # 优先查找原路径文件,找不到则尝试加.php、.html后缀 try_files $uri $uri.php $uri.html =404; }
当用户访问https://example.com/example时,Nginx会先检查是否存在example文件,不存在则尝试加载example.php,再不存在则尝试example.html,都找不到就返回404。
3. 禁止外部直接访问带扩展名的文件
使用internal指令限制.php和.html文件仅能被Nginx内部请求访问(比如try_files转发的请求),外部直接访问时返回404:
处理PHP文件
location ~ \.php$ { # 仅允许内部请求访问该location internal; # 以下是你的PHP环境配置(根据实际情况调整) fastcgi_pass unix:/run/php/php8.2-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
处理HTML文件
location ~ \.html$ { # 仅允许内部请求访问该location internal; # 指定你的HTML文件根目录 root /var/www/html; }
完整配置示例
把上述片段整合到你的server块中,最终类似这样:
server { listen 80; listen [::]:80; server_name example.com; root /var/www/example; # 重定向带扩展名请求到无版本 rewrite ^/(.*)\.(php|html)$ /$1 permanent; # 主location处理无扩展名请求 location / { try_files $uri $uri.php $uri.html =404; } # 限制PHP文件仅内部访问 location ~ \.php$ { internal; fastcgi_pass unix:/run/php/php8.2-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # 限制HTML文件仅内部访问 location ~ \.html$ { internal; root /var/www/example; } }
效果验证
- 访问
https://example.com/example.php:浏览器会被301重定向到https://example.com/example,并显示example.php的内容 - 直接用工具请求
https://example.com/example.php(不跟随重定向):服务器返回404 - 访问
https://example.com/example1.html:重定向到https://example.com/example1并显示example1.html的内容
内容的提问来源于stack exchange,提问作者FroZen Mitko
相关产品推荐
相关产品推荐

