1

我正在寻找将转换以下网址的一系列 .htaccess 语句

http://mysite.com/product           to http://mysite.com/product.php
http://mysite.com/product/55            to http://mysite.com/product.php?id=55
http://mysite.com/category/38           to http://mysite.com/category.php?id=38
http://mysite.com/resources/car/19      to http://mysite.com/resources/car.php?id=19
http://mysite.com/resources/car/19?color=red&year=2013  to http://mysite.com/resources/car.php?id=19&color=red&year=2013

换句话说,在我的网站中呈现 php 文件时,我想删除 .php 扩展名。如果 url 以数字结尾,那么我想将其作为id查询字符串参数传递。我还想将所有常规查询字符串参数传递给我的 php 我的文件,例如coloryear.

我不确定如何构建这样的 .htaccess 文件。

附加说明我目前正在使用 hte following,但它没有考虑带有数字的 url,并将其传递为id

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteCond %{QUERY_STRING} (.*)
RewriteRule . %{REQUEST_FILENAME}.php?%1 [L]

如果我可以做一些事情,比如在第二行替换 REQUEST_FILENAME 中的尾随数字,那就太好了。

4

1 回答 1

1

首先,您需要确保 Multiviews 已关闭。然后你需要 3 组重写规则:

Options -Multiviews
RewriteEngine On

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([0-9]+)$ /$1.php?id=$2 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^resources/([^/]+)/([0-9]+)$ /resources/$1.php?id=$2 [L,QSA]

如果 URL 实际上只是“产品”、“类别”和“汽车”,您可以更具体一点,那么您可以:

Options -Multiviews
RewriteEngine On

RewriteRule ^product$ /product.php [L]

RewriteRule ^(product|category)/([0-9]+)$ /$1.php?id=$2 [L,QSA]

RewriteRule ^resources/car/([0-9]+)$ /resources/car.php?id=$1 [L,QSA]

约翰(操作员) 说:

这是.htaccess我最终得到的最后一个文件

RewriteEngine On
Options -Multiviews

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^(.*)\/([0-9]+)$ $1.php?id=$2&%1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^(.*)$ $1.php?%1 [L]
于 2013-10-07T03:19:47.037 回答