user263078
user263078

Reputation:

htaccess 301 redirect with a dynamic page?

In htaccess, how do you 301 redirect dynamic pages?

For example, what if I wanted a rule that made /get.php?i=1234 to redirect to /i/1234, etcetera?

Upvotes: 1

Views: 774

Answers (2)

jpic
jpic

Reputation: 33420

Try the RedirectMatch directive with a regular expression. It depends on mod_alias so that's probably always enabled. You can use mod_rewrite for that too but it might be overkill. The replacement may contain references in the form of $n:

RedirectMatch 301 ^/get\.php\?i=([0-9]+)$ /i/$1

As you can imagine, $1 is a reference to what's matched inside the pair of parenthesis #1. You can have many references:

RedirectMatch 301 ^/get\.php\?i=([0-9]+)&y=([0-9]+)$ /i/$1/$2/

You can use an online regular expression tester to elaborate your apache config: if i put ^/get\.php\?i=([0-9]+)&y=([0-9]+)$ in the "Regexp" input, and /get.php?i=12&y=24 in the "Subject string" input, then click "Show match" it shows:

Match at position 0:
/get.php?i=12&y=24
12  # first reference available
24  # second reference available

If your regexps don't work in the tester, they not likely to work in an apache configuration. You should try them in the tester first.

Upvotes: 0

anubhava
anubhava

Reputation: 785481

You can use mod_rewrite like redirection as in this code:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} ^(i)=([^&]+)(&|$) [NC]
RewriteRule ^get\.php$ %1/%2? [L,R=301,NC]

Upvotes: 1

Related Questions