Skip to content

Instantly share code, notes, and snippets.

@waldyrfelix
Last active December 15, 2015 14:59
Show Gist options
  • Save waldyrfelix/5278764 to your computer and use it in GitHub Desktop.
Save waldyrfelix/5278764 to your computer and use it in GitHub Desktop.
redirects domain.com to www.domain.com
if (Regex.IsMatch(Request.Url.AbsoluteUri, @"^((http|https)://[^www]).*$"))
{
string newDomain = String.Format("{0}://www.{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Request.Url.AbsolutePath);
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", newDomain);
Response.End();
}
@AlbertoMonteiro
Copy link

Eu faria assim

var pattern = @"^(https?://)(?!www[.])(.+)$";
var url = Regex.Replace(Request.Url.AbsoluteUri, pattern, @"$1www.$2");

Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", url);
Response.End();

Com a regex atual: ^((http|https)://[^www]).*$
Um domínio assim: http://wordpress.com não daria um match
Detalhe o [] significa qual caracteres serão permitidos, e usando ^ como primeiro caractere dele vai ser negando os caracteres, então:
[w] == [www] => true
[^w] == [^www] => true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment