bri-design
bri-design

Reputation: 25

htaccess dynamic rewrites, SSL, non-WWW

I am trying to accomplish a few tasks using .htaccess rewrites and redirects, but am having problems getting it all to play nicely together. I am trying to accomplish three things -

  1. URLs of the form http://www.domain.com/directory/index.php?p=page need to be rewritten/redirected to http://www.domain.com/directory/page
  2. Any non-WWW requests should be redirected to www. version
  3. Only certain pages should be redirected and served under https, while everything else is redirected (if necessary) and served under http

Here's what I have currently, which is handling 1 and 2 from above. #3 is proving to be the challenge:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

#Rewrite for dynamic subpages (/directory/index.php?sitepage=page)
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ $1/index.php?sitepage=$2 [L]

#Root level pages remove php extension
RewriteRule ^([a-zA-Z0-9_-]+)$ $1.php [L]   

Any help is greatly appreciated!

Upvotes: 1

Views: 210

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

You need to make sure that the redirect is above the routing rules (the last 2):

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# All the pages that must be HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/(directory1/page1|directory1/page2|page3)
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

#Rewrite for dynamic subpages (/directory/index.php?sitepage=page)
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ $1/index.php?sitepage=$2 [L]

#Root level pages remove php extension
RewriteRule ^([a-zA-Z0-9_-]+)$ $1.php [L]   

Upvotes: 1

Related Questions