5 .htaccess Rewrites: Force HTTPS, Remove index.php, Remove .php, Force www, Force Trailing Slash

前端 未结 2 1631
心在旅途
心在旅途 2021-01-19 04:26

I\'ve read many articles and cannot seem to get ALL of the combined .htaccess Rewrites to work together. I either get re-direct loops or one or a few do not work at all.

相关标签:
2条回答
  • 2021-01-19 04:52

    Try this to avoid the loop:

    #non-www. http to www. https
    RewriteCond %{ENV:HTTPS} !on
    RewriteCond %{HTTP_HOST} ^(www\.)?yourdomain\.com$
    RewriteRule (.*) https://www.yourdomain.com/$1 [R=301,L]
    
    #non-www. https to www. https
    RewriteCond %{ENV:HTTPS} on
    RewriteCond %{HTTP_HOST} ^yourdomain\.com$
    RewriteRule (.*) https://www.yourdomain.com/$1 [R=301,L]
    
    RewriteCond %{THE_REQUEST} \s/*(.*?)/index\.php [NC]
    RewriteRule ^ %1/ [R=302,L]
    
    RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
    RewriteRule ^ /%1/ [R=302,L]
    
    # Ensure all URLs have a trailing slash.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^[^.]*?[^/.]$ %{REQUEST_URI}/ [L,R=302]
    
    # Remove all .php extensions without interfering with .js or .css.
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^([^.]+?)/?$ $1.php [L]
    
    # Remove index from url.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^.]+?)/?$ index.php?$1 [L,QSA]
    
    0 讨论(0)
  • 2021-01-19 05:19

    I see 2 issues:

    Redirect rules appearing after rewrite ones Adding .php should only happen after you ensure corresponding .php file exists.

    Have it this way:

    Options +SymLinksIfOwnerMatch
    RewriteEngine On
    RewriteBase /
    
    # Ensure www on all URLs.
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [L,R=302]
    
    # Ensure we are using HTTPS version of the site.
    RewriteCond %{HTTPS} !on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]
    
    RewriteCond %{THE_REQUEST} \s/*(.*?)/index\.php [NC]
    RewriteRule ^ %1/ [R=302,L]
    
    RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
    RewriteRule ^ /%1/ [R=302,L]
    
    # Ensure all URLs have a trailing slash.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^[^.]*?[^/.]$ %{REQUEST_URI}/ [L,R=302]
    
    # Remove all .php extensions without interfering with .js or .css.
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^([^.]+?)/?$ $1.php [L]
    
    # Remove index from url.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^.]+?)/?$ index.php?$1 [L,QSA]
    

    Make sure to clear your browser cache before testing this.

    0 讨论(0)
提交回复
热议问题