简体   繁体   中英

Rewriterule with redirect 301 and regexp not working

I have got few issues with redirect 301 and rewriterule in htaccess.

I've got few thousands subpages with new links, which have to be redirected permamently, but I can manage it with 10-20 rewriterules. But not everything is going as it should be...

Basic rewriterule works just fine, example:

RewriteRule ^subpage-([0-9]+)*\.html$ subpage.php?p=$1 [L]

It gets me from subpage-1.html to subpage.php?p=1 (no 301 needed here, it's just example, rewriterule does it's job).

Simple rewriterule with 301 redirect also works fine:

RewriteRule ^subfolder/subpage.php$ /subpage.html [L,R=301]

Althrough I don't know why I have to put "/" before "new-subpage". If I don't I'm being redirected to "domain/whole-ftp-path/new-subpage.html" and not "domain/new-subpage.html". Is it just redirect 301 thing?

And the main event:

RewriteRule ^subfolder/subpage.php?p=([0-9]+)$ /subpage-$1.html [L,R=301]

This does nothing, I'm getting domain/subfolder/subpage.php?p=1 with 404 (old subpages does not exist anymore in the same location).

What I am doing wrong?

You cannot match QUERY_STRING in RewriteRule .

Replace your .htaccess with this:

RewriteCond %{THE_REQUEST} \s/+subfolder/oldsubpage\.php\?f=([^\s&]+) [NC]
RewriteRule ^ /newsubpage-%1.html? [R=302,L]

RewriteCond %{THE_REQUEST} \s/+subfolder/oldsubpage\.php[\s/] [NC]
RewriteRule ^ /newsubpage.html? [R=302,L]

RewriteRule ^subpage-([0-9]+)*\.html$ /subpage.php?p=$1 [L,NC,QSA]

RewriteRule ^newsubpag\.html$ /newsubpage.php [L,NC]

Has to do with the query string. If you have only one subfolder you could try this:

RewriteCond %{QUERY_STRING} p=([0-9]+)
RewriteRule .*$ /subpage-%1.html [L,R=301]

With more subfolders you could try:

RewriteRule ^subfolder/subpage.php(.*)$ /subpage$1 [QSA]

RewriteCond %{QUERY_STRING} p=([0-9]+)
RewriteRule ^(.*)$ /$1-%1.html [L,R=301]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM