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


SEO friendly URL instead of query string .htaccess

如何修改.htaccess文件并获得SEO友好的URLS而不是查询字符串。我想实现这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=红色

在另一个帖子上@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]

第二点很有效,但我想知道在之前或之后,我必须把其他规则放在哪里。我把这个放在另一个规则后面,但它不起作用,因为它重定向到以前的urllocalhost/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]

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

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]