How to remove parts of URL by rewrite in htaccess

点点圈 提交于 2019-12-13 15:48:15

问题


I tried to apply other answers found on StackOverflow, but nothing worked.

I have old links in Google, which people are visiting, but the structure of my page has changed and if people call those links, the page will be displayed messed up.

I have links like these:

/PIXMA/Canon-PRINT-Inkjet/SELPHY-664425773
/PL/SQL-Timestamp/Dawsons-Integral-Calculator-903670995
/--/-HDPrime-Dictionary-E-K/두산동아-중학교-교과서2007개정-교육-과정-429617286

I want to keep only the last part behind the last slash, like these:

/SELPHY-664425773
/Dawsons-Integral-Calculator-903670995
/두산동아-중학교-교과서2007개정-교육-과정-429617286

My htaccess looks like this now:

AddDefaultCharset utf-8
RewriteEngine On
Options +FollowSymlinks

RewriteRule ^robots\.txt$ robots-subdomains.txt

#ErrorDocument 404 /404.php

RewriteRule ^cat/([a-zA-Z_-]+)/([0-9]+)$ /404.php [NC]
RewriteRule ^cat/([a-zA-Z_-]+)$ /404.php [NC]
RewriteRule ^grossing/([a-zA-Z_-]+)/([0-9]+)$ /404.php [NC]
RewriteRule ^app/([a-zA-Z_-]+)/([a-zA-Z0-9_-]+)/([0-9]+)$ /$2-$3 [R=301,NC]

#This is the final output
RewriteRule ^(.+)-([0-9]+)$ appsite.php?title=$1&id=$2

As you see, there are some rewrite rules already there, which I want to redirect to 404. Those are not the issue.

I want to redirect those wrongly formatted, but still existing URLs redirect to the sites formatted like the last row in the htaccess.

The problem is, I don't know the texts and formatting (the number of slashes) in the URL, because they were generated on the fly. The only certain thing is the last part of the URL behind the last slash.

Can somebody tell me, how to cut all the things before the last slash?


回答1:


This can be done by using:

RewriteRule ^.*/([^/]+-[0-9]+)$ /$1 [R=301]

This will redirect every request where the url ends with anything-NUMBER, e.g. www.example.com/xxx/yyy/foobar-123 --> www.example.com/foobar-123

[R=301] will force a redirect with HTTP 301 "Moved permanently". That will tell all search engines that they should delete the old URLs and instead use the new ones.



来源:https://stackoverflow.com/questions/33731862/how-to-remove-parts-of-url-by-rewrite-in-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!