Handle query parameters recursively using htaccess

2019-06-03 05:16发布

问题:

I am here again with the query of re-writing URL :(.
I am using htaccess for re-writing, below is my htaccess code:

RewriteEngine On
RewriteBase /

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} !-f 
RewriteCond %{REQUEST_URI} !\.\w+$
RewriteCond %{REQUEST_URI} !/$ 
RewriteRule (.*) /$1/ [R,L]

RewriteCond %{REQUEST_URI} ^/([\w\d-]+)/$ [NC]
RewriteRule ^ /?file_name=%1 [L,QSA]

RewriteCond %{QUERY_STRING} !^$
RewriteCond %{QUERY_STRING} (?:(.*)&)?file_name=([\w\d-]+)(.*) [NC]
RewriteRule ^ %2/?%1%3 [L,R]

Before asking my queries let me give you short explanation about how above code is working. I have a URL like http://www.mysite.com/ (for index) and other pages could be executed by using a parameter called file_name=page_name like http://www.mysite.com/?file_name=my_blog. My htaccess is helping me to exclude the file_name parameter and make a new URL like http://www.mysite.com/my_blog/.

Now I do have a query:

  1. Right now there is already a parameter file_name and now I want to give extra parameters like http://www.mysite.com/?file_name=my_blog&blog_alias=welcome-to-new-generation and wanted this to look like http://www.mysite.com/my_blog/welcome-to-new-generation/. So if I add any number of parameter there parameter name should be removed and only parameter value comes with slash.
    Please note: Parameter name could be anything.

Please please please help.

回答1:

This is a very interesting problem that requires recursive implementation of mod_rewrite rules. Put this code in your .htaccess:

Update II As per further comments, redirects /?file_name=my_blog&blog_alias=welcome-to-new-generation&foo=bar&n=v URI to /file_name+my_blog/blog_alias+welcome-to-new-generation/foo+bar/n+v

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# forwards ?file_name=my_blog&blog_alias=welcome-to-new-generation to
# /file_name=my_blog&blog_alias=welcome-to-new-generation
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+\?([^\s]+)\s [NC]
RewriteRule ^$ %1? [L]

# redirects /file_name=my_blog&blog_alias=welcome-to-new-generation&foo=bar&n=v
# to /file_name+my_blog/blog_alias+welcome-to-new-generation/fo+barn+/v    
RewriteRule ^(.*/)?([^=]+)=([^&]+)&(.*)$ $1$2+$3/$4 [L]
RewriteRule ^(.*/)?([^=]+)=(.*)$ $1$2+$3 [L,R]

# internal forward from /file_name+my_blog/blog_alias+welcome-to-new-generation to
# /?file_name=my_blog&blog_alias=welcome-to-new-generation
RewriteRule ^([^\+]+)\+([^/]+)/(.*)$ $3?$1=$2 [L,QSA]
RewriteRule ^([^\+]+)\+([^/]+)/?$ /?$1=$2 [L,QSA]

Once you're sure it is working change R to R=301