繁体   English   中英

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

[英]How can I use .htaccess to hide .php URL extensions?

我想在我的.htaccess文件中添加一些内容,这将隐藏我的 php 文件的.php文件扩展名,因此转到 www.example.com/dir/somepage 会显示它们 www.example.com/dir/somepage.php。

有什么可行的解决方案吗? 我的网站使用 HTTPS,如果这很重要的话。

这是我现在的 .htaccess:

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 中使用此代码:

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,这将随后影响所有此类请求,使其落入此重定向,并可能导致此类请求停止工作。

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

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

删除 php 分机

您可以使用 /.htaccess 中的代码:

RewriteEngine on


RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_FILENAME}.php [NC,L]

使用上面的代码,您将能够访问 /file.php 作为 /file

删除 html 扩展

RewriteEngine on


RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_FILENAME}.html [NC,L]

注意:'RewriteEngine on' 指令应该在 per.htaccess 顶部使用一次,所以如果你想结合这两条规则,只需从第二条规则中删除该行。 您还可以删除您选择的任何其他扩展名,只需将代码中的 .php 替换为它们即可。

快乐.htaccessing!

<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f       # if the requested URL is not a file that exists
RewriteCond %{REQUEST_FILENAME} !-d       # and it isn't a directory that exists either
RewriteCond %{REQUEST_FILENAME}\.php  -f  # but when you put ".php" on the end it is a file that exists
RewriteRule ^(.+)$ $1\.php [QSA]          # then serve that file (maintaining the query string)

</IfModule>

奇怪的是,这段代码在 Windows 中的 XAMPP 中尝试时给了我 HTTP 500 个错误。删除注释修复了它。 移动注释也是如此,使它们在自己的行中,而不是与说明在同一行。

试试这个:

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]Try:

参考:

如何隐藏.htaccess中的.php扩展名

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM