简体   繁体   中英

Regular expression and URL Rewriting

I have a URL http://abc.com/v2/ and now i want that if anyone put the URL something like this http://abc.com/v2/abc or http://abc.com/v2/xyz should be redirected to http://abc.com/

in general i want that anything put after /v2/ must be redirected to http://abc.com/

Please also tell me how to learn more about URL rewriting (for Apache environment) and Regular expression

Also that's a pretty basic rule then:

 RewriteRule  ^v2/  http://abc.com/   [R]

The [R] flag is for redirection, but in this case implied anyway. And the ^ start of subject marker would simply replace the leading / in your example.

As resources: http://regular-expressions.info/ for a regex tutorial, and ServerFault: Everything You Ever Wanted to Know about Mod_Rewrite Rules but Were Afraid to Ask? for the RewriteRules, as well as the current manual: http://httpd.apache.org/docs/current/mod/mod_rewrite.html

The first link in Google for "apache url rewriting":

http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

I used mod_rewrite myself, it isn't hard. Please put forth a bit more effort before asking other people to Google things for you.

Here's the good RewriteRule you may apply:

RewriteRule  ^v2/(.*)  /$1   [QSA,R=301]

As for your other question, I do agree with Eric Johnson but here are my 2c:

Two hints to help you doing the job faster:


Please try to use the RewriteLog directive: it helps you to track down problems:

# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On

My favorite tool to check for regexp:

http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)

You use this tool when you want to check the URL and see if they're valid or not.

You can put on start page. Or create auto include file with this code:

$value = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$pattern = "http://abc.com/v2/";
$rez = str_replace($pattern,"",$value);

if(strlen($rez)>0){
    echo "Here";
    header("Location: http://abc.com");
}

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