Sean Cunningham
Sean Cunningham

Reputation: 3106

htaccess redirect fails with multiple URL parameters

I've got the following htaccess file:

RewriteEngine On
RewriteBase /

# Redirect to remove .php 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

# Redirect to "page" for dynamic pages
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ page?url=/$1 [L]

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

This allows my custom CMS to use dynamic URLs (http://example.com/some-page, for example) and redirect it to http://example.com/page?url=some-page so that the CMS can render the content. It all works great - until someone adds a URL like http://example.com/something/else. When I spit out the url parameter with: print $_GET['url']; I get /something/else.php/else.

So it seems like the remove .php directive is getting lost and the second parameter is getting duplicated? Thanks for any help.

Upvotes: 2

Views: 687

Answers (1)

anubhava
anubhava

Reputation: 784928

Have it this way:

Options -MultiViews
RewriteEngine On

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

RewriteCond %{ENV:REDIRECT_STATUS} =200
RewriteRule ^ - [L]

# Redirect to remove .php 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]

# Redirect to "page" for dynamic pages
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule !^page\.php$ page.php?url=%{REQUEST_URI} [L,NC,QSA]

Here are changes:

  1. Keep redirect rule before rewrite rules otherwise when www is removed from a URL then your internal URL will be exposed.
  2. Use page.php in target instead of page to avoid another rewrite rule execution.
  3. Use [L] flag in .php adding rule.
  4. Addition of Options -MultiViews

Upvotes: 2

Related Questions