Dynamic URL rewrite using .htaccess

2019-07-20 14:07发布

问题:

I am pretty new to .htaccess rewrites, and I'm trying to create rules to dynamically rewrite the URLs.

For example, say the user enters the following URL:

http://example.com/xxx/?user=2002

It would be rewritten into:

http://example.com/xxx/user/2002/

If user passes multiple parameters like this:

http://example.com/xxx/?user=2002&activity=100&result=true

It should become:

http://example.com/xxx/user/2002/activity/100/result/

Note: All the query strings will be dynamically generated.

This is what I have come up with:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /news/

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /news/index.php [L]
</IfModule>

Update

I tried to make the above code and query string rewrite code to work together. The modified .htaccess looks like below:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /news/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /news/index.php [L]

# first take out query string from your /xxx/ URLs
RewriteCond %{QUERY_STRING} ^.+$
RewriteRule ^news/?$ %{REQUEST_URI}/%{QUERY_STRING}? [L]

# now convert & to /
RewriteRule ^([^&]+)&(.*)$ $1/$2 [L]

# now convert = to /
RewriteRule ^([^=]+)=([^=]+=.*)$ $1/$2 [L]    
RewriteRule ^([^=]+)=([^=]+)$ $1 [L,R]

# internal rule to replace /n1/v1/n2/v2 to QUERY_STRING
RewriteRule "^(news)/([^/]+)/([^/]*)(/.*)?$" /$1$4?$2=$3 [L,QSA]
</IfModule>

回答1:

Really tricky rules these are. Put these recursive rules in your root .htaccess:

RewriteEngine On
RewriteBase /news/

# first take out query string from your URLs
RewriteCond %{THE_REQUEST} \?\S+
RewriteRule ^/?$ %{QUERY_STRING}? [L]

# now convert all & to /
RewriteRule ^([^&]+)&(.*)$ $1/$2 [L]

# now convert all = to /
RewriteRule ^([^=]+)=([^=]+=.*)$ $1/$2 [L]
RewriteRule ^([^=]+)=([^=]+)$ $1/$2 [L,R]

# finally an internal rule to replace /n1/v1/n2/v2 to QUERY_STRING
RewriteRule "^([^/]+)/([^/]*)(?:/(.*))?$" $3?$1=$2 [L,QSA]

## Your existing stuff followed now
RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]