Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess redirect 4 specific pages to https

I have a problem where I need to redirect 4 specific pages on my website to their https secure versions.

I currently have an htaccess file which is redirecting both example.com and www.example.com to https://example.com

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.*\.)*example.com$ [NC]
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://example.com/$1 [R] 

what I need is something like

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.*\.)*example.com/page1.php$ [NC]
RewriteCond %{HTTP_HOST} ^(.*\.)*example.com/page2.php$ [NC]
RewriteCond %{HTTP_HOST} ^(.*\.)*example.com/page3.php$ [NC]
RewriteCond %{HTTP_HOST} ^(.*\.)*example.com/page4.php$ [NC]
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://example.com/page1.php$1 [R] 
RewriteRule ^(.*)$ https://example.com/page2.php$1 [R] 
RewriteRule ^(.*)$ https://example.com/page3.php$1 [R] 
RewriteRule ^(.*)$ https://example.com/page4.php$1 [R] 

Notice that I have removed the third RewriteCond line from the above code as I don't want every page on my website to be displaying https only the pages I specifically state.

How can I resolve this problem?

PS also, is this line covering both www.example.com and example.com?

RewriteCond %{HTTP_HOST} ^(.*\.)*example.com$ [NC]

I'm assuming that

^(.*\.)*

has something do with it?

like image 216
daniel blythe Avatar asked Mar 09 '12 12:03

daniel blythe


2 Answers

Options +FollowSymlinks
RewriteEngine On
RewriteBase /

#redirect www.mydomain.com to mydomain.com (or any other subdomain)
RewriteCond %{HTTP_HOST} !^mydomain.com$ [NC]
RewriteRule ^(.*)$ http://mydomain.com/$1 [L,R=301]

#force https for certain pages    
RewriteCond %{HTTPS} !=on
RewriteRule ^(page1\.php|page2\.php|page3\.php|page4\.php)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]
like image 189
Gerben Avatar answered Oct 21 '22 00:10

Gerben


I have modified and cleaned up your code. You can use this code in your .htaccess file in $DOCUMENT_ROOT:

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

# HTTPS is not already on
RewriteCond %{HTTPS} !=on
# Redirect to HTTPS is URI is page1.php OR page2.php OR page3.php OR page4.php
RewriteRule ^page[1234]\.php$ https://mydomain.com%{REQUEST_URI} [L,R]
like image 35
anubhava Avatar answered Oct 21 '22 02:10

anubhava