Rewriting urls back and forth using mod_rewrite

2019-07-27 07:07发布

问题:

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 ?

回答1:

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


回答2:

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.