删除 PHP 扩展名并使用 .htaccess 重写查询字符串


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

我正在尝试重组现有网站,同时将URL重写为更用户友好的格式。我现在拥有的是http://example.com/test_vars.php?test_var1=value1&test_var2=value2,理想情况下,我想要的是http://example.com/test_vars/test_var1/value1/test_var2/value2

诚然,我是修改htaccess文件的新手,但是已经完成了我的研究并尝试了一些事情。我最接近我正在寻找的内容(诚然不是那么接近(,但我附上了下面的代码:

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

有了这个,我最终得到了一个 URL http://example.com/test_vars.php/test_var1/value1/test_var2/value2但是,没有一个变量被传递到页面。

test_vars.php 中,您必须手动解析参数。$_SERVER['REQUEST_URI']将包含/test_var1/value1/test_var2/value2 .例如,编写一个简单的函数来解析带有 explode() 的字符串。

如果您的网址没有".php"扩展名,请更改此行

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

对此:

RewriteRule ^test_vars test_vars.php

现在你有了漂亮的网址:http://example.com/test_vars/test_var1/value1/test_var2/value2