Andrew M
Andrew M

Reputation: 4288

Mod_Rewrite with Query Strings In Pretty URLs

I have an .htaccess file that redirects all URLs to the index.php file with a route query string parameter:

# Enable Mod_rewrite
RewriteEngine on

# Redirect pretty URLs to the index file
RewriteRule ^([\w\/\-]+)/?$ index.php?route=$1

This works great, with the exception of URLs with query strings in them. For example, I have a form that redirects back to the login screen with an error code (/admin/login?error=1). Obviously, the problem is, the $_GET[error] parameter is never passed to the main script.

How would I get these parameters passed to the script?

Upvotes: 1

Views: 1687

Answers (3)

da5id
da5id

Reputation: 9146

This is my standard mod_rewrite entry (altered for your question). I'm adding it to save anyone potential pain with stuff like images & includes. It redirects everything except existing files.

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([\w\/\-]+)/?$ index.php?route=$1 [QSA]
</IfModule>

Upvotes: 3

Lawrence Cherone
Lawrence Cherone

Reputation: 46660

Just add [QSA] as a flag:

'qsappend|QSA' (query string append) This flag forces the rewrite engine to append a query string part of the substitution string to the existing string, instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.

RewriteRule ^([\w\/\-]+)/?$ index.php?route=$1 [QSA]

Upvotes: 7

Scott Stevens
Scott Stevens

Reputation: 2651

Set the flag QSA - Query String Append

# Enable Mod_rewrite
RewriteEngine on

# Redirect pretty URLs to the index file
RewriteRule ^([\w\/\-]+)/?$ index.php?route=$1 [QSA]

(All I did was add the [QSA] )

The Apache Mod_Rewrite Documentation has more on flags.

Upvotes: 2

Related Questions