.htaccess to convert query string never works

2019-09-17 00:19发布

问题:

The goal: To have a query string converted into a nice looking URL, which I have never gotten to work.

The details: Change this URL: http://www.mywebsite.com/static-directory/index.php?state=florida&city=tallahassee

to this one: http://www.mywebsite.com/static-directory/florida/tallahassee

What I have tried: Well, just about everything. My latest search came up with this tutorial...

I have my .htaccess file in my root directory (httpdocs).

Any help or point me at the right answered question on Stack Overflow.

Thanks.

回答1:

QUESTION:
"Change this URL: .../static-directory/index.php?state=florida&city=tallahassee
to this one: .../static-directory/florida/tallahassee"

According to the question, all is needed is to convert the 1st URL (The Request) with the query to the 2nd one without a query.

Here is a way to achieve that in one .htaccess file at root directory:

Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} /static-directory/index.php\?state=([^&]+)&city=([^\s&]+) [NC]
RewriteRule  ^static-directory/index.php  /static-directory/%1/%2? [R=301,L,NC]

However, just in in case the OP forgot to mention the whole idea is to remove the query in order to have a "pretty" URL but still get the data from the original URL, add next 2 lines to the rule-set:

RewriteCond %{REQUEST_URI}  !index\.php [NC]
RewriteRule  ^static-directory/([^/]+)/([^/]+) /static-directory/index.php?state=$1&city=$2 [L]