SEO友好的URL而不是查询字符串.htaccess

Est*_*des 1 php .htaccess seo url-rewriting clean-urls

如何修改.htaccess文件并获取SEO友好URL而不是查询字符串.我想实现这3个目标:

  1. localhost/example/products /而不是 localhost/example/products-list.php
  2. localhost/example/products/38 /而不是 localhost/example/products.php?id = 38
  3. localhost/example/products/38/red /而不是 localhost/example/products.php?id = 38&color = red

在另一篇文章中@anubhava给了我很多帮助,这就是我现在对第二点的看法:

RewriteEngine on
RewriteBase /example
# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /products(?:\.php)?\?id=([^\s&]+) [NC]
RewriteRule ^ products/%1? [R=302,L,NE]
# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^products/([^/]+)/?$ products.php?id=$1 [L,QSA]
Run Code Online (Sandbox Code Playgroud)

第二点是正常的,但我想知道在之前或之后我必须在哪里放置其他规则.我把它放在另一条规则之后,但它没有用,因为它重定向到上一个url localhost/example/products/38 /:

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /products(?:\.php)?\?id=([^\s&]+)\?color=([^\s&]+) [NC]
RewriteRule ^ products/%1/%2? [R=302,L,NE]
# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^products/([^/]+)/([^/]+)/?$ products.php?id=$1&color=$2 [L,QSA]
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 6

您需要2个参数的新规则集:

RewriteEngine on
RewriteBase /example/

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /products(?:\.php)?\?id=([^\s&]+)&color=([^\s&]+) [NC]
RewriteRule ^ products/%1/%2/? [R=302,L,NE]

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

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# internal forward from pretty URL to actual one
RewriteRule ^products/([^/]+)/?$ products.php?id=$1 [NC,L,QSA]

RewriteRule ^products/([^/]+)/([^/]+)/?$ products.php?id=$1&color=$2 [NC,L,QSA]

RewriteRule ^products/?$ products-list.php [L,NC]
Run Code Online (Sandbox Code Playgroud)