.htaccess for appending https://www [closed]

2019-07-11 02:39发布

问题:

I have searched for quite sometime to get a solution or a hint to my query but didnt find anything valuable. Basically i have my application which is SSL secured. All i want is that

  1. If users try to open the application without https and www, it should automatically append "https://www"

  2. If user enters "https://mydomain.com", it should change to "https://www.mydomain.com"

  3. If user enters "www.mydomain.com", it should change to "https://www.mydomain.com"

I understand this can be achieved through .htaccess but i am a lot ignorant about the way these files are written.

Any help will be highly appreciated.

回答1:

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

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


回答2:

Try adding these rules to the htaccess file in your document root:

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


回答3:

Use the following:

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.mydomain.com/$1 [R,L]


回答4:

In your .htaccess file

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://www.mydomain.com/$1 [L,R]
</IfModule>

RewriteCond %{HTTPS} off checks if HTTPS is off. If it is indeed off (the URL doesn't contain https://), then the rewrite rule applies and the user is redirected.