user2924019 user2924019 - 12 days ago 8
Apache Configuration Question

Using multiple rules for URL Rewrite (.htaccess)

I've been struggling with getting my URL's to redirect correctly.

What I would like to happen

To forward to https://www.ourwebsite.co.uk if any of the following happens:


  • User accesses the website from ( http:// OR https:// )ourwebsite.com / .net / .org / .mobi / .eu

  • User doesn't enter from HTTPS (443)

  • User enters the site without www.

  • Basically, they have to visit the website via https://www.ourwebsite.com or not at all.



What is happening now



My .htaccess file currently contains:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?ourwebsite\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?ourwebsite\.net$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?ourwebsite\.eu$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?ourwebsite\.mobi$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?ourwebsite\.it$ [NC]
RewriteRule ^(.*)$ https://www.ourwebsite.co.uk/$1 [R=301,L]

RewriteCond %{SERVER_PORT} !443
RewriteRule ^(.*)$ https://www.ourwebsite.co.uk/$1 [R=301,L]


I have tried...

I have tried many different examples I found online, they work individually but they don't seem to work together. I have split the non 443 rule and added it separate at the bottom, but this hasn't changed anything.

Answer

You can do this in a single redirect rule:

RewriteEngine On

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !=www.ourwebsite.co.uk
RewriteRule ^ https://www.ourwebsite.co.uk%{REQUEST_URI} [R=301,L,NE]

# rest of rules go below this

Make sure to clear your browser cache before testing this change.