Gregor
Gregor

Reputation: 81

How exactly does mod_rewrite work when displaying old url

I have used mod_rewrite to change http://mywebsite.com/?page=2 to http://mywebsite.com/page/2 using the following code:

    RewriteEngine On
    RewriteRule ^page/([^/]*)\.php$ /?page=$1 [L]

But when i type in the old url - http://mywebsite.com/?page=2 the page still appears and the url doesnt change to the static one. Is mod-rewrite meant to redirect the user or just make everything on the dynamic url appear on the static one when entered? If so how can i redirect any user that goes to the old dynamic url - http://mywebsite.com/?page=2 to the new static one http://mywebsite.com/page/2? Plus does google still index the old url?

This is my complete .htaccess file:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [NC,L]

    # external redirect from actual URL to pretty one
    RewriteCond \s/+\?page=([^\s&]+) [NC]
    RewriteRule ^ /page/%1? [R=301,L]

    # existing rule
    RewriteRule ^page/([^/]+)/?$ /?page=$1 [L,QSA]

Upvotes: 1

Views: 138

Answers (2)

anubhava
anubhava

Reputation: 784958

Have your full .htaccess like this:

RewriteEngine On

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

# existing rule
RewriteRule ^page/([^/]+)/?$ /?page=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [L]

Upvotes: 2

Normal9ja
Normal9ja

Reputation: 91

mod_rewrite necessarily will not redirect the visitor to the new fancy URL, but it will make sure that anybody who visits the new URL will still access it as if it is using the old URL

I believe you can achieve something like that with mod_substitute, but that's not something I will advice you to do now.

If you can, manually change the links to reflect the new changes, or have a function which will parse out your links such as

http://mywebsite.com/?page=2 to http://mywebsite.com/page/2

such as

function fancyuri($url){
    //blah blah, strip out ? and change all occurence of equality sign = to forward slash
    //do some other tricks
    //return formatted links 
}

And then pass your links as a param to the function and have it return your nice urls, in this case, even if you don't want it again, you can strip off the formatting codes in the function and still have ur original url returned.

Upvotes: 0

Related Questions