0

I need to rewrite url on my PHP website but I'm not sure about the syntax.

I want to redirect :

'some_url?id=1' => 'new_url/1'

And when user type this :

'new_url/1'

I want him to be backend redirect to :

'some_url?id=1'

UPDATE: My last try:

RewriteRule /site/?id=$1    /site/$1
1
  • I'm a rewriting noob, last try : 'RewriteRule /site/?id=$1 /site/$1' Commented Oct 2, 2017 at 8:30

2 Answers 2

2

You can use:

RewriteEngine on
RewriteBase /

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+some_url\?id=([^\s&]+) [NC]
RewriteRule ^ /new_url/%1? [R=301,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^new_url/(.+?)/?$ some_url?id=$1 [L,QSA,NC]
Sign up to request clarification or add additional context in comments.

Comments

0

You can't match the query string in rewrite rules. You need to use a rewrite condition instead.

Stuff matched there with () can then be used in the rewrite rule with the %n notation (as opposed to $n.

So what you are looking for is something along these lines:

RewriteCond %{QUERY_STRING} id=([0-9]+)
RewriteRule ^some_url($|/) /new_url/%1?

Demo here:

http://htaccess.mwl.be?share=0e31a7bf-9711-533d-896b-461177c46ca2

1 Comment

However, you'll need an additional condition to prevent a redirect/rewrite loop when rewriting back to the "real" URL. One way is to check against THE_REQUEST (instead of QUERY_STRING), as Croises has done in his answer, or check against ENV:REDIRECT_STATUS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.