开发者

RewriteRule to redirect with url that got parameters

开发者 https://www.devze.com 2023-02-09 08:44 出处:网络
I am trying to use RewriteRule inorder to redirect form x page to y page. x page got two parameters > products.php?product=$1&page=$2 (myweb.com/products.php?prod...)

I am trying to use RewriteRule inorder to redirect form x page to y page. x page got two parameters > products.php?product=$1&page=$2 (myweb.com/products.php?prod...) y should be $1/$2/ (myweb.com/$1/$2/)

I tried this one >

Options +FollowSymlinks
RewriteEngine on
RewriteBase /
RewriteRule ^products.php?product=(.*) $1/ [R=301,L]

just for testing, and some similiar codes like > /$1/ instead $1/, only $1 I tried to use RewriteCond with query_string but nothing worked....

ofc that there's continue to the htaccess >

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

and some more rules which are not relevant (I think)

Can you help me please?

Thanks.

EDIT:

After some massive searches I found the answer! this is the answer开发者_高级运维:

RewriteCond %{QUERY_STRING} ^product=(.*)$
RewriteRule ^test.php$ %1/? [R=301,L]

now for the explanation: first of all, added rewritecondition that will match the query string. second I remove the query string from the rewrite rule and the $ = the continue (the query string). I also needed to add ? (question mark) at the second part of the rewriterule > %1/? the question mark mean that I dont want to preserve the query string in the new url.


The first part of your rule should contain a regular expression against which the server can compare the request. For instance:

RewriteRule ^([^/]+)/?  index.php?page=$1 [L]

That would take http://somedomain.fake/somepage/ and redirect it to http://somedomain.fake/index.php?page=somepage. The first part of the rule matches, the second part handles. My rule there, "([^/]+)", is regular expression that will match anything. If you want to narrow the way your rule works, you can customize the regular expression to include or exclude certain string parts.

I suggest you consider adding the follow conditions above your rule. They ensure that if the file or directory that matches the rule actually exists, the server does not override the actual files with the rewrite.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

.htaccess and mod_rewrite is voodoo, to use an old quote. Be sure you research thoroughly before implementing this kind of thing on a live site.

--------------------- Edit:

Updated after discussion:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^product=([^/]+)$
RewriteRule ^products\.php$ %1.php [L]

OR

RewriteEngine On
RewriteCond %{QUERY_STRING} ^product=([^/]+)$
RewriteRule ^products\.php$ %1/ [L]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号