Apache rewrite: dir/file.php?foo=bar&name=val -> file.php?newparam=dir&foo=bar&name=val
What is the .htaccess code for the following URL rewrite:
www.example.com/dir/file.php
into
www.example.com/file.php?newparam=dir
and
www.example.com/dir/file.php?param1=val1¶m2=v开发者_运维问答al2
into
www.example.com/file.php?newparam=dir¶m=val1¶m2=val2
Thanks in advance.
Try the following, let me know if it works:
RewriteEngine on
RewriteBase /
# Allow files that exist to bypass rewrites
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite remaining files
RewriteRule ^/([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+\.php)$ /$2?newparam=$1 [L,QSA]
This only allows dir
and file.php
containing alphanumeric characters, underscore and dash.
The final rule looks for a URI matching two path components, between the forward slashes. The first must be 1 or more characters in the given set [-a-zA-Z0-9_]+
, the second must be the same, but ending in .php
. The ^
and $
characters match the front and back of the URI. The replacement says put the second bracketed group (the file.php
part) at the front, and put the first bracketed group (the dir
part) as a parameter called newparam
. The [L,QSA]
at the end says that this is the Last [L]
rule if it matches, so stop matching further and perform the redirect and the [QSA]
means "Query String Append", which adds the original query string to the end again, leaving that off would remove the original query string.
精彩评论