Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

redirect - Redirecting “.htaccess” with same folder & file name

A while ago I rebuilt a site that was on a CMS. As expected the Google search console regularly comes up with URLs that generate 404 crawling errors which I would promptly redirect to their new equivalents using a 301 on a .htaccess file.

The issue is that I came across the URL of an old page which looked like this:

http://www.example.com/example 

The new page is now called http://www.example.com/example.php.

There is, however, a folder called example too so if I add a redirect like this:

Redirect 301 /example http://www.example.com/example.php

everything in that folder also gets redirected, so a URL called http://www.example.com/example/product.php would now show up as http://www.example.com/example.php/product.php.

Is there a way to redirect the old URL successfully without having to rename the folder example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please clear your browser cache and then put the following code at main root .htaccess file :

DirectorySlash Off 
RewriteEngine on 
RewriteCond %{THE_REQUEST} s/+example [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)  /$1.php [R=302,L]

The code above will stop directoryslash and make it off so no file without slash goes to be directory as default and then check if example exists in QUERY_STRING and the trick comes here in this line RewriteCond %{REQUEST_FILENAME}.php -f,it will check if adding .php to this string , is that really file in directory or not ? and already we have example.php in root so , it will go to last line to redirect any string that passed the rules above to itself.php and that what you want exactly.

The above code will catch any example in only root directory with example only but if wanna inherit other sub-folders or apply this rule to entire site so , whenever there is string without extension the priority will be for the file , put the following code at your main root .htaccess file :

DirectorySlash Off 
RewriteEngine on 
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)  /$1.php [R=302,L]

After testing this code , if it is Ok , change 302 to 301 to be permanent redirection


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...