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

问题描述:

我想在我的 .htaccess 文件中放一些东西,它会隐藏我的 php 文件的 .php 文件扩展名,所以去 www.example.com/dir/somepage 会显示 www.example.com/dir/somepage.php.

I want something to put in my .htaccess file that will hide the .php file extension for my php files, so going to www.example.com/dir/somepage would show them www.example.com/dir/somepage.php.

是否有任何可行的解决方案?我的网站使用 HTTPS(如果这很重要的话).

Is there any working solution for this? My site uses HTTPS, if that matters at all.

这是我目前的 .htaccess:

This is my .htaccess at the moment:

RewriteEngine On

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

ErrorDocument 404 /error/404.php

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

在 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]