.htaccess友好的URL

4

请问有谁能帮我进行URL重写吗?

我有以下代码:

www.example.com/index.php?page=namepage
www.example.com/index.php?page=gallery&topic=nametopic
www.example.com/index.php?page=homepage&paging=1

我希望你能为我提供以下内容:

www.example.com/namepage
www.example.com/gallery/nametopic
www.example.com/homepage/1

在我的htaccess文件中,我有以下内容:

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

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)?/?$ ?page=$1&topic=$2

但是它并不是很好用,因为我可以写:
  • www.example.com/index.php?page=namepage(页面或其他内容)
  • www.example.com/?page=namepage(页面或其他内容)
  • www.example.com/namepage/
  • www.example.com/namepage(这个我想要 - 没有其他的)
第二个问题是:
  • www.example.com/namepage(好的,我想要,我们看到namepage)
  • www.example.com/namepage/whatever(不好,我想要404,但我们看到了namepage)
  • www.example.com/gallery/topic(好的,我想要,我们看到nametopic)
  • www.example.com/whatever/whatever2/whatever3(好的,我想要404)
非常感谢任何人。
1个回答

7
### all your redirects

# for www.example.com/index.php?page=homepage&paging=1
RewriteCond %{THE_REQUEST} \?page=([^&]+)&paging=([0-9]+)
RewriteRule ^ /%1/%2? [L,R=301]

# for www.example.com/index.php?page=gallery&topic=nametopic
RewriteCond %{THE_REQUEST} \?page=([^&]+)&topic=([^&\ ]+)
RewriteRule ^ /%1/%2? [L,R=301]

# for www.example.com/index.php?page=namepage
RewriteCond %{THE_REQUEST} \?page=([^&\ ]+)($|\ )
RewriteRule ^ /%1? [L,R=301]

# for www.example.com/namepage/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/$ /$1 [L,R=301]

### all your rewrites back

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

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)$ /index.php?page=$1&topic=$2 [L]

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接