user3312792 user3312792 - 1 year ago 160
PHP Question

mod rewrite url with two variables

I want to rewrite post.php?id=1&title=test to post/1/test

I have this code:

RewriteRule ^post/([^/]+)/([^/]+)/?$ post.php?id=$1&title=$2 [L,QSA]

This only works if I rename post.php links to /post in my php file. I want to rewrite the urls so that I don't need to edit any links.

Similar to below:

RewriteCond %{THE_REQUEST} \s/+(post)\.php[?/\s] [NC]
RewriteRule ^ %1 [R=301,L]

RewriteRule ^(post)/?$ $1.php [L]

Answer Source

You can use:

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

# internal forward from pretty URL to actual one
RewriteRule ^post/([^/]+)/([^/]+)/?$ post.php?id=$1&title=$2 [L,QSA,NC]

But it is wrong to say "I don't need to edit any links". Because it is a method to correct the old links already referenced, not to prevent you from changing your code in your pages. Because HTML code still contains bad links...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download