简体   繁体   中英

Force HTTPS on .htaccess but only on production

I have been looking around for a snippet of code that will force https:// . I've found this:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The problem is when I want to work on local so a url like "localhost" or "example.dev" it tries to redirect to https://localhost (it doesn't work).

How do I solve this?

(so to sum it all up, I want the snippet above to work only when I use it on production, eg "example.com")

I want the snippet above to work only when I use it on production, eg example.com )

You can restrict your rule to only target example.com using a rewrite condition:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]

This is somewhat advanced but you can try to put your servers in a file called servers.txt

RewriteEngine on
RewriteMap lb rnd:servers.txt
RewriteRule ^/(.*) http://${lb:servers}/$1 [P,L]
serverlist.txt will contain a list of the servers:

## serverlist.txt file con
servers localhost.example.com|server1.example.com

The above answer is good enough with local and production differences in mod rewrite behavior. I would version the .htaccess in git or subversion (which ever you use) in that case.

This is mainly for load balancing but you can apply that in your mechanism.

For Apache, put your rules within <IfModule mod_ssl.c></IfModule> block, and disable ssl module on your local server.

<IfModule mod_ssl.c>
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM