如何为seo友好的url编写htaccess重写规则

时间:2015-01-27 10:35:40

标签: .htaccess mod-rewrite

  • 我刚接触.htaccess
  • 我需要URLs的一些重写规则。
  • 我谷歌有些并申请但没有更改网址。

我想:

demo.example.com/section.php?id=1 

更改为:

demo.example.com/section/sample-section

我试过

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^section/(\d+)*$ ./section.php?id=$1

但没有区别

感谢。

感谢您的帮助。

2 个答案:

答案 0 :(得分:8)

首先,确保Apache配置中 mod_rewrite 已启用且htaccess文件允许

然后,将此代码放入您的htaccess(必须位于根文件夹中)

Options -MultiViews
RewriteEngine On

# redirect "/section.php?id=xxx" to "/section/xxx"
RewriteCond %{THE_REQUEST} \s/section\.php\?id=([0-9]+)\s [NC]
RewriteRule ^ /section/%1? [R=301,L]

# internally rewrite "/section/xxx" to "/section.php?id=xxx"
RewriteRule ^section/([0-9]+)$ /section.php?id=$1 [L]

答案 1 :(得分:2)

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

这会将example.com/section.php?id=X变为example.com/section/X

我建议将URI存储在数据库中,然后使用section.php?uri =

例如:

example.com/section.php?uri=super-awesome

会变成:

example.com/section/super-awesome