简体   繁体   中英

Redirect to www, https and add a trailing slash using .htaccess

This is my current .htaccess:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule .* - [L]

RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?p=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?p=$1

RewriteRule ^([a-zA-Z0-9_-]+)/(.*)$ index.php?p=$1&a=$2

It works, but I would like to simplify it to avoid unnecessary redirects.

I need to redirect the user to the WWW subdomain, HTTPS protocol and add the trailing slash if needed, with as least as possible redirects.

Can somebody suggest a way to achieve this?

Thanks!

You can reduce it as:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^/?$ https://www.domain.com [R=301,L]

RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule ^(.+?)/?$ https://www.domain.com/$1/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule .* - [L]

RewriteRule ^([\w-]+)/?$ index.php?p=$1 [L,QSA]    
RewriteRule ^([\w-]+)/(.+)$ index.php?p=$1&a=$2 [L,QSA]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM