使用.htaccess Not Working为PHP中的博客创建自定义友好URL

时间:2017-09-17 08:38:38

标签: php .htaccess mod-rewrite

我的网址是这样的:http://example.com/blog/blog.php?id=38 并在blog.php我正在使用$_GET并显示有关博客的标题和所有说明。

但是,我希望这样做:http://example.com/blog/this-can-be-blog-title

我已经尝试过这个.htaccess,使其至少看起来像这样:http://example.com/blog/blog/id/38/

Options +FollowSymLinks
RewriteEngine on
RewriteRule blog/id/(.*)/ blog.php?id=$1
RewriteRule blog/id/(.*) blog.php?id=$1                 

但即使这样也行不通。网址没有变化。我错过了什么?

2 个答案:

答案 0 :(得分:0)

试试这个.htaccess

   RewriteEngine on  
   RewriteBase /
 # mod_rewrite ignore rules if a matching file or directory exists
   RewriteCond %{REQUEST_FILENAME} -f [NC,OR] 
   RewriteCond %{REQUEST_FILENAME} -d [NC] 
   RewriteRule .* - [L]


 # generate url
   RewriteRule ^(.*)$  blog/blog.php?url=$1 [NC,L,QSA]

您需要通过URL GET参数从数据库中获取具有“this-can-be-blog-title”slug的正确页面,而不再需要基于id的查询。

如果您只想将id作为GET参数传递,请使用:

   RewriteEngine on  
   RewriteBase /
 # mod_rewrite ignore rules if a matching file or directory exists
   RewriteCond %{REQUEST_FILENAME} -f [NC,OR] 
   RewriteCond %{REQUEST_FILENAME} -d [NC] 
   RewriteRule .* - [L]


 # generate url
   RewriteRule ^blog/id/(.*)$  blog/blog.php?url=$1 [NC,L,QSA]

答案 1 :(得分:0)

您可以使用:

Options +FollowSymLinks -Multiviews
RewriteEngine on

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+blog/blog\.php\?id=(\d+) [NC]
RewriteRule ^ /blog/id/%1? [R=301,L,NE]

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