Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess redirect http to https

I have an old url (www1.test.net) and I would like to redirect it to https://www1.test.net
I have implemented and installed our SSL certificate on my site.
This is my old file .htaccess:

RewriteEngine On RewriteRule !\.(js|gif|jpg|png|css|txt)$ public/index.php [L] RewriteCond %{REQUEST_URI} !^/public/ RewriteRule ^(.*)$ public/$1 [L] 

How can I configure my .htaccess file so that url auto redirect to https?
Thanks!

like image 293
Bàn Chân Trần Avatar asked Nov 14 '12 09:11

Bàn Chân Trần


People also ask

Does .htaccess do redirect?

Use a 301 redirect . htaccess to point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "example.com" domain.

Should you redirect http to HTTPS?

It's a perfectly acceptable "bootstrap" method - 301 redirect from HTTP to HTTPS then on the HTTPS side return a Strict-Transport-Security header in order to lock the browser into HTTPS.


2 Answers

I use the following to successfully redirect all pages of my domain from http to https:

RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 

Note this will redirect using the 301 'permanently moved' redirect, which will help transfer your SEO rankings.

To redirect using the 302 'temporarily moved' change [R=302,L]

like image 81
Bradley Flood Avatar answered Sep 21 '22 01:09

Bradley Flood


Update 2016

As this answer receives some attention, I want to hint to a more recommended way on doing this using Virtual Hosts: Apache: Redirect SSL

<VirtualHost *:80>    ServerName mysite.example.com    Redirect permanent / https://mysite.example.com/ </VirtualHost>  <VirtualHost _default_:443>    ServerName mysite.example.com    DocumentRoot /usr/local/apache2/htdocs    SSLEngine On # etc... </VirtualHost> 

Old answer, hacky thing given that your ssl-port is not set to 80, this will work:

RewriteEngine on  # force ssl RewriteCond     %{SERVER_PORT} ^80$ RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R] 

Note that this should be your first rewrite rule.

Edit: This code does the following. The RewriteCond(ition) checks wether the ServerPort of the request is 80 (which is the default http-port, if you specified another port, you would have to adjust the condition to it). If so, we match the whole url (.*) and redirect it to a https-url. %{SERVER_NAME} may be replaced with a specific url, but this way you don't have to alter the code for other projects. %{REQUEST_URI} is the portion of the url after the TLD (top-level-domain), so you will be redirected to where you came from, but as https.

like image 28
Jojo Avatar answered Sep 24 '22 01:09

Jojo