.htaccess友好的URl

时间:2012-09-21 21:33:41

标签: .htaccess mod-rewrite rewrite

有人可以帮我修改一些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(好的,我想,我们看到名称页面)
  • www.example.com/namepage/whatever(不行,我想404,但我们看到名页)
  • www.example.com/gallery/topic(好的,我想,我们看到了nametopic)
  • www.example.com/whatever/whatever2/whatever3(好的,我想要404)

非常感谢任何人。

1 个答案:

答案 0 :(得分: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]