Search code examples
regex.htaccessmod-rewritephp-deployer

htaccess remove segment from url and redirect to https and www


I am deploying a Craft CMS site to a shared hosting account using Deployer.

The latest deployment is accessible from domain.com/current/public

My .htaccess file looks like the following, which strips current/public from the url and forces https:

RewriteEngine on
RewriteRule ^(.*)$ current/public/$1
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

I now need to also redirect all urls to use www

How can I adjust my .htaccess to force www on all urls?

*** UPDATE ***

I have managed to solve the above with the following:

RewriteEngine on
RewriteRule ^(.*)$ current/public/$1
RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+) [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]

When I go to example.com/admin it redirects to example.com/current/public/admin. How can I adjust my htaccess file to remove 'current/public' from admin urls?


Solution

  • Your http->https and www adding rule should be top most rule so that it works on original URI instead of a rewritten URI due to other rule.

    RewriteEngine on
    
    RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+) [NC]
    RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
    
    RewriteRule ^(.*)$ current/public/$1 [L]
    

    Make sure to clear browser cache before testing this rule.

    Also add this redirect rule in /current/public/.htaccess:

    RewriteCond %{THE_REQUEST} /current/public/(\S+) [NC]
    RewriteRule ^ /%1 [R=301,L,NE]