且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 .htaccess 隐藏 .php URL 扩展名?

更新时间:2022-11-27 09:11:27

在 DOCUMENT_ROOT 下的 .htaccess 中使用此代码:

Use this code in your .htaccess under DOCUMENT_ROOT:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L,NE]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

需要注意的是,这也将影响所有 HTTP 请求,包括 POST,随后将影响所有此类请求归入此重定向,并可能导致此类请求停止工作.

It should be noted that this will also effect all HTTP requests, including POST, which will subsequently effect all requests of this kind to fall under this redirection and may potentially cause such requests to stop working.

要解决这个问题,您可以在第一个 RewriteRule 中添加一个例外以忽略 POST 请求,因此不允许他们使用该规则.

To resolve this, you can add an exception into the first RewriteRule to ignore POST requests so the rule is not allowed to them.

# To externally redirect /dir/foo.php to /dir/foo excluding POST requests
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L,NE]