Home > Software engineering >  htaccess http to https for domain and domain/paths
htaccess http to https for domain and domain/paths

Time:12-15

I need to convert all http access to a domain including its potential pages under the main page, to its https equivalent. What I have now just directs all Domain and www.Domain access to https://Domain but not pages that are off the main page. How can I modify the htaccess commands so in addition I can get http://Domain/other-web-pages to go to https://Domain/other-web-pages

RewriteEngine On 
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule (.*) https://example.com [L,R=301]

CodePudding user response:

You are close. The redirection works, but you need to actually hand over the requested path too:

RewriteEngine On 
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [QSA,L,R=301]

Such general should get implemented in the actual http server's central host configuration. If you have no access to that you can use a distributed configuration file instaed. Such file has to be placed inside the http server's DOCUMENT_ROOT folder.

CodePudding user response:

(An alternative to @arkascha's answer, that builds on your existing code.)

:
RewriteRule (.*) https://example.com [L,R=301]

You are already capturing the requested URL-path (ie. (.*)) but not passing this through to the substitution string. So, all you need is the corresponding backreference ($1) that contains the URL-path. For example:

:
RewriteRule (.*) https://example.com/$1 [L,R=301]

And, if you have other directives, this needs to go near the top of the .htaccess file before any existing rewrites.

You will need to clear your browser cache before testing, since any erroneous 301 (permanent) redirects to the homepage will have been cached by the browser. Test with 302 (temporary) redirects to avoid such caching issues.

  • Related