Overview
I'm trying to rewrite:
http://www.foo.com/bar
to the secure version https://www.foo.com/bar
, thenhttps://www.foo.com/bar
to https://www.foo.com/index.php?location=bar
My index.php
page simply outputs the $_GET
variables.
Code
.htaccess
:
RewriteEngine On
RewriteBase /
RewriteRule ^https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent]
RewriteRule ^([^/]*)$ /?location=$1 [L]
index.php
:
<?php print_r($_GET); exit; ?>
Issue
www.foo.com/bar
, I see a 500 Server Error.$_GET
"location" variable and visit foo.com
, it doesn't redirect to the secure version of the site.Update
.htaccess
:
RewriteEngine on
# if https is off (it is on)
#RewriteCond %{HTTPS} off
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ ?location=$1 [L,QSA]
Visiting the following results in a redirect loop error:
However, if I comment out this line:
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
the page loads as expected:
Array ( [location] => bar )
This leads me to believe that the issue lies with the HTTPS redirect, how can I solve this?
This rule is the problem:
RewriteRule ^https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent]
As syntax is
RewriteRule matching-pattern target [flags]
Also you need to RewriteCond
in both rules to avoid rules looping.
You can fix it by replacing your code with:
DirectoryIndex index.php
RewriteEngine on
# if https is off
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ ?location=$1 [L,QSA]