将HTTPS添加到现有的Mod Rewrite

时间:2016-12-08 14:45:38

标签: apache mod-rewrite

我在mod_rewrite中有以下规则和条件,并希望为其添加HTTPS。我想在发布之前确认以下内容是准确的。

当前规则和条件

    RewriteEngine On
    RewriteCond %{REQUEST_URI} \.jpg$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* /home/domain.com/public_html/missing.png [L]
    RewriteCond %{HTTP_HOST} ^www.olddomain.com$
    RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} !^$
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteRule ^index.html$ http://www.domain.com/ [L,R=301]

新规则和条件

    RewriteEngine On
    RewriteCond %{REQUEST_URI} \.jpg$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* /home/domain.com/public_html/missing.png [L]
    RewriteCond %{HTTP_HOST} ^www.olddomain.com$
    RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]
    RewriteCond %{HTTPS} Off
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} !^$
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteRule ^index.html$ https://www.domain.com/ [L,R=301]

1 个答案:

答案 0 :(得分:0)

RewriteEngine On
# always do domain/https redirs first
RewriteCond %{HTTPS} =off [OR]
RewriteCond %{HTTP_HOST} ^(?!www\.domain\.com$). [NC]
RewriteCond %{THE_REQUEST} ^\S+\s+/?(\S*)
RewriteRule ^ https://www.domain.com/%1 [NS,NE,L,R=301]
# remove index files from URLs, except from POST forms, etc. you can add more file extensions to the second condition
RewriteCond %{REQUEST_METHOD} ^(?:GET|HEAD)$
RewriteCond %{THE_REQUEST} ^\S+\s+/?((?:[^?/]*/)*?)index\.(?:html?|php|pl)(\?\S*)?(?:\s|$)
RewriteRule ^ https://www.domain.com/%1%2 [NS,NE,L,R=301] 
# missing images
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule \.(?:jpe?g|png|gif)$ /missing.png [NS,NC,L,DPI]