Sunday, April 3, 2022

[SOLVED] Apache rewrite for URI, capture pages/folders

Issue

I am trying to accomplish the following... if a user comes to the site via 123abc.com (with or without www), and 123abc.com/hello (with or without www) they should automatically be taken to https://www.123abc.com/URI_IF_NEED ...

this is what I have so far. the base domain redirects correctly but any URL structures with pages/dir following it does not.

trying to achieve https://www.123abc.com and/or https://www.123abc.com/hello

ServerName www.123abc.com
ServerAlias 123abc.com
DocumentRoot "/mnt/var/www/html/"

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

Solution

You don't need a complex rewrite for this. Just create different virtual servers and let non-www redirect on www(443/https) and a single one for (80/http)

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # real server configuration
</VirtualHost>

PS: Credits apache redirect from non www to www

If you still want to write the way you were, then you can write it like below

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI}   [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}   [R=301,L]

Tested on online tester

https://htaccess.madewithlove.be/

Different test results

Test 1

Test 2

Test 3

Test 4



Answered By - Tarun Lalwani
Answer Checked By - Dawn Plyler (WPSolving Volunteer)