Damiano Barbati
Damiano Barbati

Reputation: 3496

Url rewrite with php

What's wrong with this htaccess? I'm trying to redirect everything that has a question mark like "www.mysite.com/?bla=bla" to "www.mysite.com/router.php?bla=bla

AddDefaultCharset UTF-8
RewriteEngine On
RewriteRule ^([\w]{1,7})$ short.php?p=$1 [L]
RewriteRule ^([\w]+)\.html$ html/$1.html [L]
RewriteRule ^([\w]+)\.php$ php/$1.php [L]
RewriteRule ^\?(.+)$ router.php?$1 [L]

Each rule works except for the last one, which returns me a:

Forbidden

You don't have permission to access / on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

Upvotes: 1

Views: 250

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270609

You cannot access the querystring inside a RewriteRule. Instead, use RewriteCond to match it. Using the ? in the position you have it treats it as a special character for the regular expression.

Instead use:

# Prevent redirect loop
# Place above all other rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Non-empty querystring goes to router
RewriteCond %{QUERY_STRING} ^(.+)
# Rewrite to router appending existing querystring (QSA)
RewriteRule ^/?$ router.php [L,QSA]

Addendum:

Prevent the router from going into the php directory with:

RewriteCond %{REQUEST_FILENAME} !^router\.php
RewriteRule ^([\w]+)\.php$ php/$1.php [L]

Upvotes: 2

Related Questions