maddisoj
maddisoj

Reputation: 587

Redirect /search?query=foo to /search/foo

I am trying to redirect /search?query=foo to /search/foo but all my attempts have failed.

I have tried the solutions in similar questions but they have not worked. I believe this is because I am trying to rewrite the request to index.php so that the PHP framework can process it.

I know that it is not the PHP framework causing the issue as when I manually go to /search/foo it is handled correctly.

My .htaccess looks like this:

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/search$
RewriteCond %{QUERY_STRING} ^query=(.*)$
RewriteRule ^ search/%1 [R=302,NS]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

I don't understand why it's not working as when I look at the logs the URL is successfully being transformed into what I'm after:

applying pattern '^' to uri 'search'
RewriteCond: input='/search' pattern='^/search$' => matched
RewriteCond: input='query=asd' pattern='^query=(.*)$' => matched
rewrite 'search' -> 'search/asd'
add per-dir prefix: search/asd -> .../app/public/search/asd
explicitly forcing redirect with http://localhost/.../app/public/search/asd

Upvotes: 1

Views: 370

Answers (1)

Jon Lin
Jon Lin

Reputation: 143896

You need to get rid of the query string. Instead of:

RewriteCond %{REQUEST_URI} ^/search$
RewriteCond %{QUERY_STRING} ^query=(.*)$
RewriteRule ^ search/%1 [R=302,NS]

Try:

RewriteCond %{THE_REQUEST} \ /+search\?query=([^&\ ]+)
RewriteRule ^ search/%1? [L,R=302,NS]

The important part is the ? after the backreference, %1. This tells mod_rewrite that the new query string is just ? (i.e. nothing). Othewise the existing query string automatically gets appended to the rewritten URL/redirect.

Upvotes: 2

Related Questions