如何从网页中删除该文件类型,而不创建新目录并将文件命名为index.php。我想要 http://example.com/google.html 到 http://example.com/google。
我将如何去做这件事。
PS:我尝试查看其他一些教程,但有些令人困惑。我现在可以在 .htaccess 中完成
是的,我知道这个问题已经被问过多次并得到回答,但我会根据我的经验给出更全面的答案。
这是可以帮助您的 .htaccess 代码片段:
# Apache Rewrite Rules
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# Add trailing slash to url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]
# Remove .php-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)/$ $1.php
# End of Apache Rewrite Rules
</IfModule>
我想在这里强调一些重要的事情,供大家参考:
index.php
被许多 PHP 框架使用).php
扩展名,如果您还想删除其他扩展名(例如 .html
),请复制并粘贴第三块并将 php
替换为其他扩展名。@armanP 上面接受的答案不是来自 php url 的
remove
.php 扩展名。它只是使得访问 php 文件成为可能,而无需在末尾使用 .php
。例如,可以使用 /file.php
或 /file
访问 /file.php
,但这样您就有 2 个不同的 url 指向同一位置。
如果你想完全删除
.php
,你可以在/.htaccess
中使用以下规则:
RewriteEngine on
#redirect /file.php to /file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC]
RewriteRule ^ /%1 [NE,L,R]
# now we will internally map /file to /file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [L]
要删除 .html ,请使用此
RewriteEngine on
#redirect /file.html to /file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.html [NC]
RewriteRule ^ /%1 [NE,L,R]
# now we will internally map /file to/ file.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)/?$ /$1.html [L]
Apache 2.4* 用户的解决方案:
如果您的apache版本是2.4,您可以使用不带
RewriteConditions
的代码。在Apache 2.4上,我们可以使用END
标志而不是RewriteCond
来防止无限循环错误。
这是针对 Apache 2.4 用户的解决方案
RewriteEngine on
#redirect /file.php to /file
RewriteRule ^(.+).php$ /$1 [L,R]
# now we will internally map /file to /file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [END]
注意:如果您的外部样式表或图像 添加这些规则后不会加载,要解决此问题,您可以将链接绝对更改为
<img src="foo.png>
为 <img src="/foo.png>
。注意文件名之前的 /
。或者更改 URI 基础,将以下内容添加到网页的头部 <base href="/">
。
您的网页无法加载 css 和 js,原因如下:
当您的浏览器网址从
/file.php
更改为 /file
时,服务器认为 /file
是一个目录,并尝试将其附加到所有相对路径的前面。例如:当您的网址为http://example.com/file/
时,您的相对路径更改为<img src "/file/foo.png">
,因此图像无法加载。您可以使用我在上一篇中提到的解决方案之一来解决此问题。
这是删除 .php 时内部路径的修复(使用上面的代码作为参考)。
# Start of Apache Rewrite Rules
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase
# From http:// to https://
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
# Redirect /file.php to /file with POST (enabled)
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC]
RewriteRule ^ /%1 [NE,L,R]
# Add trailing slash to url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [L]
# Remove .php-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)/$ $1.php
</IfModule>
# End of Apache Rewrite Rules
注:
上面是接受不带.php的URL的代码,带.php的URL将被转换为不带.php(.php将被删除)所有具有各自路径的文件/文件夹将正常打开,没有任何问题,发布和获取方法也可以正常工作。