douzai9405
douzai9405
2013-01-12 17:15

使用mod_rewrite来回重写URL

Maybe it will seem a very simple question, my website's url are awfully written, so I want to rewrite them. So I am preparing to activate mod_rewrite. The question is the following:

Suppose my url switches from site_url/index.php?page=mypage&type=mytype to site_url/mypage/mytype, what will happen if one refresh the page, is it necessary to put in the .htaccess file the converse process for proceeding to rewriting ?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongsicheng5262 dongsicheng5262 8年前

    You need a combination of redirect and rewriting. A draft outline of URL rewriting process would be:

    • If URL contains .php, 301/302 redirect the request to its SEO friendly version. This will change the address in browser address bar.
    • If SEO friendly URL was requested, rewrite it to its PHP version. This will not change the address in browser address bar.

    Here is a very basic example of rewrite rules that do both of the above:

    #
    # redirect /index.php?page=somepage&type=sometype to friendly url
    # 
    RewriteCond %{THE_REQUEST} /index\.php
    RewriteCond %{QUERY_STRING} page=(\w+)&type=(\w+)
    RewriteRule ^index\.php$ /%1/%2? [R,L]
    
    #
    # rewrite /somepage/sometype to index.php
    # 
    RewriteRule ^(\w+)/(\w+)$ index.php?page=$1&type=$2
    
    点赞 评论 复制链接分享
  • doujia3441 doujia3441 8年前

    In .htaccess, you should be making a forward which maps...

    ^/(mypage)/(mytype) to index.php?page=$1&type=$2
    

    But the reverse should be left alone. So a direct request to site_url/index.php?page=mypage&type=mytype would simply be passed as is.

    So, a refresh won't change anything.

    点赞 评论 复制链接分享

为你推荐