【问题标题】:How to remove .php extension from URL on server and on localhost with .htaccess file?如何使用 .htaccess 文件从服务器和本地主机上的 URL 中删除 .php 扩展名?
【发布时间】:2020-03-19 01:56:37
【问题描述】:

正如标题所说,我需要从带有 .htaccess RewriteRule 的 URL 中删除 .php。

https://example.com/about.php

应该是

https://example.com/about

localhost:8080/about.php

应该是

localhost:8080/about

这是我当前的.htaccess 文件:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [NC,L]
</IfModule>

【问题讨论】:

    标签: php .htaccess


    【解决方案1】:

    您可以将其添加到您的 .htaccess 文件中,它会从 URL 中删除 .php 扩展名:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [NC,L]
    

    【讨论】:

    • 检查 mod_rewrite 模块是否启用。创建 php 文件并写入 &lt;?php phpinfo() ?&gt; 并打开 url 。确保加载的模块中有mod_rewrite
    • 您的解决方案适用于服务器,但不适用于 localhost。在 localhost 上,它试图重写,但最终陷入循环。
    • 我将我的 xampp 端口更改为 8081,它仍然可以作为 localhost:8081/about 工作。也许你做错了什么。
    【解决方案2】:

    您可以在站点根目录 .htaccess 中使用这些规则:

    RewriteEngine On
    
    # To externally redirect /dir/file.php to /dir/file
    RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
    RewriteRule ^ /%1 [R=301,NE,L]
    
    ## To internally rewrite /dir/file to /dir/file.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]
    

    【讨论】:

    • 从 .php 重定向的方式很好,但是当这种情况发生时,它会从 https 重定向到 http。
    • 不,我建议的规则不会发生这种情况。你能发布你完整的 htaccess inn 问题吗
    • 添加了我当前的文件
    • 好的,所以你需要在我的回答中用这个建议的代码替换所有现有的 .htaccess 。请注意,我的代码中没有http://https://,因此如果您看到https -&gt; http 发生,则可能是由于您的代码或Apache 配置中的某些内容。为了测试我建议在 Chrome 开发工具 中使用 缓存禁用 进行测试,并在“网络”选项卡中检查您获得的 301/302 重定向 URL 是什么。
    猜你喜欢
    • 2012-11-12
    • 2014-06-29
    • 2022-01-21
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多