清除URLS www.to non,删除index.php,删除.php扩展名,使用HTACCESS添加尾部斜杠


Clean URLS www. to non, remove index.php, remove .php extention, add trailing slash using HTACCESS

所以我似乎可以找到其中一些的解决方案,但无法让它们一起工作。我想做的是从各个方面创建干净的URLS。

  1. 解决所有www.和非www。转到非www.页面
  2. 删除所有出现的index.php(即,如果导航到文件夹/blog/index.php,则解析为/blog/)
  3. 从所有URLS中删除php扩展名(即/page.php到/page/)
  4. 添加尾部斜线(即/page到/page/)

这就是我目前所拥有的:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)/$ $1.php [L]

这就完成了清除URL的操作,删除了.php扩展名并添加了尾部斜杠。我不得不删除www.to-non并删除index.php,因为干净的url和尾随斜杠停止工作。提前谢谢大家。

以下是您的.htaccess应该是什么样子:

RewriteEngine On
# Remove www.
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www'.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
# Remove file extensions, add a trailing slash.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !('.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

这是一篇关于从URL中删除文件扩展名的非常好的参考文章。请记住,要使其工作,您必须在所有链接中引用非扩展版本,例如<a href="about">About</a>,而不是<a href="about.php">About</a>

当您在做.htaccess的事情时,我可能还建议添加以下片段。前两个与网站速度有关,第二个用于自定义404页面,第三个用于强制UTF-8(因此您不必在HTML中声明它)。

# Expires caching (Caching static files for longer drastically improves performance, you might even want to put even more aggressive times)
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
# Gzip 
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
# 404 Page
ErrorDocument 404 /404.php
# Force UTF-8
AddDefaultCharset utf-8

如果你感兴趣的话,我在CodePen上的一篇博客文章中写到了这一点。

HTML BP有一个疯狂的700+行.htaccess,你可以看到一些很酷的技巧。