我正在寻找一系列会转换以下网址的.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我的文件,如color
和year
。
我不确定如何构建这样的.htaccess文件。
其他说明
我目前正在使用hte跟随,但它没有考虑跟踪数字的网址,并将其传递为id
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteCond %{QUERY_STRING} (.*)
RewriteRule . %{REQUEST_FILENAME}.php?%1 [L]
如果我能在第二行中替换REQUEST_FILENAME中的尾随数字,那就太棒了。
答案 0 :(得分:1)
首先,您需要确保关闭多视图。那么你需要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]
如果网址实际上只是“产品”,“类别”和“汽车”,您可以更具体一点,那么您可以拥有:
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]