简体   繁体   中英

Removing PHP extension and re-writing query string with .htaccess

I'm trying to restructure an existing website and, at the same time, re-write the URLs to a more user-friendly format. What I have now is http://example.com/test_vars.php?test_var1=value1&test_var2=value2 and, ideally, what I would like is http://example.com/test_vars/test_var1/value1/test_var2/value2

Admittedly, I'm new to modifying htaccess files, however have done my research and tried out a few things. The closest I've come to what I'm looking for (admittedly is not that close), but I've enclosed the code below:

Options +FollowSymLinks
Options +Indexes
RewriteEngine on
DirectoryIndex index.html

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(([^/]+/)*[^.]+)$ /$1 [L]

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.html
RewriteRule .* index.html

With this, I end up with a URL of http://example.com/test_vars.php/test_var1/value1/test_var2/value2 however, none of the variables are being passed to the page.

In your test_vars.php , you have to manually parse the parameters. The $_SERVER['REQUEST_URI'] will contain /test_var1/value1/test_var2/value2 . Write a simple function to parse the string with explode() , for example.

And to have your URL without the ".php" extension, change this line

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

To this:

RewriteRule ^test_vars test_vars.php

Now you have your pretty URL: http://example.com/test_vars/test_var1/value1/test_var2/value2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM