6 .htaccess 重写:删除index.html、删除.html、强制非www、强制尾部斜杠

Gha*_*man 3 php regex wordpress .htaccess mod-rewrite

我必须提供一些有关我的网站环境的信息

  1. 我的根目录中有静态网页。

  2. WordPress 安装在子词典 www.domain.com/blog/ 中

  3. 我有两个 .htaccess ,一个在根目录中,一个在 wordpress 文件夹中。

我想要

  • 所有 URL 上的 www 到非< 下面的代码做到了:)
  • 从 url < 下面的代码中删除 index.html 是吗:)
  • 删除所有 .html 扩展名/将 301 重定向到不带 .html 扩展名的 url < 下面的代码做到了:)
  • 将尾随斜杠添加到静态网页/从非尾随斜杠重定向 301 << 我需要帮助
  • 强制尾随斜杠到 Wordpress 网页/从非尾随斜杠重定向 301 < 下面的代码做到了:)

一些例子

域名.tld/index.html >> 域名.tld/

域名.tld/file.html >> 域名.tld/file/

域名.tld/file.html/ >> 域名.tld/file/

域名.tld/wordpress/post-name >> 域名.tld/wordpress/post-name/

我在 ROOT htaccess 中的代码是

    <IfModule mod_rewrite.c> 
    Options +FollowSymLinks -MultiViews


    RewriteEngine On 
    RewriteBase /

    #removing trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d     
    RewriteRule ^(.*)/$ $1 [R=301,L]

    #www to non
    RewriteCond %{HTTP_HOST} ^www\.(([a-z0-9_]+\.)?domain\.com)$ [NC]
    RewriteRule .? http://%1%{REQUEST_URI} [R=301,L]

    #html
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^([^\.]+)$ $1.html [NC,L]

    #index redirect 
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.html\ HTTP/ 
    RewriteRule ^index\.html$ http://domain.com/ [R=301,L]
    RewriteCond %{THE_REQUEST} \.html 
    RewriteRule ^(.*)\.html$ /$1 [R=301,L] 
    </IfModule> 

    <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /blog/
    # Force Trailing Slash for wordpress
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)[^/]{1}$ %{REQUEST_URI}/ [L,R=301]
    </IfModule> 
Run Code Online (Sandbox Code Playgroud)

上面的代码做了

  1. 将 www 重定向到非 www
  2. 删除末尾的尾部斜杠(如果存在)
  3. 删除index.html
  4. 删除所有 .html
  5. 将 301 重定向到文件名,末尾不带斜杠
  6. 对 WordPress 强制尾随斜杠并从末尾的非尾随斜杠重定向 301

编辑

#removing trailing slash Rule usage
Run Code Online (Sandbox Code Playgroud)

删除尾部斜杠规则

anu*_*ava 5

对于站点根 .htaccess 来说是这样的:

<IfModule mod_rewrite.c> 
Options +FollowSymLinks -MultiViews

RewriteEngine On 
RewriteBase /

#www to non
RewriteCond %{HTTP_HOST} ^www\.(([a-z0-9_]+\.)?domain\.com)$ [NC]
RewriteRule ^(.+?)/?$ http://%1/$1/ [R=301,L]

RewriteCond %{THE_REQUEST} \s/+(.+?)\.html/?[\s?] [NC]
RewriteRule ^ /%1/ [R=301,NE,L]

#index redirect 
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.html\ HTTP/ 
RewriteRule ^index\.html$ http://%{HTTP_HOST}/ [R=301,L]

# add a trailing slash to non files
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=301,NE]

# add html internally
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^([^.]+)/$ $1.html [L]

</IfModule>
Run Code Online (Sandbox Code Playgroud)

确保在测试之前清除浏览器缓存。