从url中删除.php和id,并用斜杠替换

时间:2013-12-23 07:25:59

标签: php regex .htaccess mod-rewrite url-rewriting

我在htaccess中尝试了很多url重写规则,但现在我被卡住了。我必须改变这个网址

products.php?id=31

products/31 

我用过

   Options +FollowSymLinks -MultiViews
   # Turn mod_rewrite on
   RewriteEngine On
   RewriteBase /

  ## don't touch /forum URIs
  RewriteRule ^forums/ - [L,NC]

  ## hide .php extension snippet

  # To externally redirect /dir/foo.php to /dir/foo
  RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
  RewriteRule ^ %1 [R,L]

  # To internally forward /dir/foo to /dir/foo.php
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}.php -f
  RewriteRule ^(.*?)/?$ $1.php [L]

使用此我得到以下结果:

products?id=31

但这不起作用。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

让您的完整.htaccess像这样:

  Options +FollowSymLinks -MultiViews
  # Turn mod_rewrite on
  RewriteEngine On
  RewriteBase /

  ## don't touch /forum URIs
  RewriteRule ^forums/ - [L,NC]

  RewriteCond %{THE_REQUEST} \s/+products(?:\.php)?\?id=([0-9]+) [NC]
  RewriteRule ^ products/%1? [R,L]

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

  ## hide .php extension snippet
  # To externally redirect /dir/foo.php to /dir/foo
  RewriteCond %{THE_REQUEST} \s([^.]+)\.php [NC]
  RewriteRule ^ %1 [R,L]

  # To internally forward /dir/foo to /dir/foo.php
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}.php -f
  RewriteRule ^(.+?)/?$ $1.php [L]

答案 1 :(得分:0)

你需要像那样使用它

RewriteRule ^products/([0-9]+)$ products.php?id=$1

答案 2 :(得分:0)

使用下面的htaccess规则

RewriteRule ^products/([0-9]*)$ /product.php?id=$1 [L,QSA]