C# 如何使用“www”网址重定向到没有“www”网址的网址,反之亦然?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/521804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect with "www" URL's to without "www" URL's or vice-versa?
提问by Prashant
I am using ASP.NET 2.0 C#. I want to redirect all request for my web app with "www" to without "www"
我正在使用 ASP.NET 2.0 C#。我想将带有“www”的网络应用程序的所有请求重定向到不带“www”的
www.example.com to example.com
www.example.com 到 example.com
Or
或者
example.com to www.example.com
example.com 到 www.example.com
Stackoverflow.com is already doing this, I know there is a premade mechanism in PHP (.htaccess) file. But how to do it in asp.net ?
Stackoverflow.com 已经这样做了,我知道 PHP (.htaccess) 文件中有一个预制机制。但是如何在 asp.net 中做到这一点?
Thanks
谢谢
采纳答案by Zhaph - Ben Duguid
I've gone with the following solution in the past when I've not been able to modify IIS settings.
过去,当我无法修改 IIS 设置时,我使用了以下解决方案。
Either in an HTTPModule (probably cleanest), or global.asax.cs in Application_BeginRequest or in some BasePage type event, such as OnInit I perform a check against the requested url, with a known string I wish to be using:
在 HTTPModule(可能是最干净的)或 Application_BeginRequest 中的 global.asax.cs 或某些 BasePage 类型事件(例如 OnInit)中,我对请求的 url 执行检查,并使用我希望使用的已知字符串:
public class SeoUrls : IHttpModule
{
#region IHttpModule Members
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
public void Dispose()
{
}
#endregion
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
HttpContext ctx = ((HttpApplication) sender).Context;
IHttpHandler handler = ctx.Handler;
// Only worry about redirecting pages at this point
// static files might be coming from a different domain
if (handler is Page)
{
if (Ctx.Request.Url.Host != WebConfigurationManager.AppSettings["FullHost"])
{
UriBuilder uri = new UriBuilder(ctx.Request.Url);
uri.Host = WebConfigurationManager.AppSettings["FullHost"];
// Perform a permanent redirect - I've generally implemented this as an
// extension method so I can use Response.PermanentRedirect(uri)
// but expanded here for obviousness:
response.AddHeader("Location", uri);
response.StatusCode = 301;
response.StatusDescription = "Moved Permanently";
response.End();
}
}
}
}
Then register the class in your web.config:
然后在您的 web.config 中注册该类:
<httpModules>
[...]
<add type="[Namespace.]SeoUrls, [AssemblyName], [Version=x.x.x.x, Culture=neutral, PublicKeyToken=933d439bb833333a]" name="SeoUrls"/>
</httpModules>
This method works quite well for us.
这种方法对我们来说效果很好。
回答by shsteimer
There's a Stackoverflow blog post about this.
有一篇关于这个的 Stackoverflow 博客文章。
http://blog.stackoverflow.com/2008/06/dropping-the-www-prefix/
http://blog.stackoverflow.com/2008/06/dropping-the-www-prefix/
Quoting Jeff:
引用杰夫:
Here's the IIS7 rule to remove the WWW prefix from all incoming URLs. Cut and paste this XML fragment into your web.config file under
<system.webServer> / <rewrite> / <rules> <rule name="Remove WWW prefix" > <match url="(.*)" ignoreCase="true" /> <conditions> <add input="{HTTP_HOST}" pattern="^www\.domain\.com" /> </conditions> <action type="Redirect" url="http://domain.com/{R:1}" redirectType="Permanent" /> </rule>
Or, if you prefer to use the www prefix, you can do that too:
<rule name="Add WWW prefix" > <match url="(.*)" ignoreCase="true" /> <conditions> <add input="{HTTP_HOST}" pattern="^domain\.com" /> </conditions> <action type="Redirect" url="http://www.domain.com/{R:1}" redirectType="Permanent" /> </rule>
这是从所有传入 URL 中删除 WWW 前缀的 IIS7 规则。将此 XML 片段剪切并粘贴到您的 web.config 文件中
<system.webServer> / <rewrite> / <rules> <rule name="Remove WWW prefix" > <match url="(.*)" ignoreCase="true" /> <conditions> <add input="{HTTP_HOST}" pattern="^www\.domain\.com" /> </conditions> <action type="Redirect" url="http://domain.com/{R:1}" redirectType="Permanent" /> </rule>
或者,如果您更喜欢使用 www 前缀,您也可以这样做:
<rule name="Add WWW prefix" > <match url="(.*)" ignoreCase="true" /> <conditions> <add input="{HTTP_HOST}" pattern="^domain\.com" /> </conditions> <action type="Redirect" url="http://www.domain.com/{R:1}" redirectType="Permanent" /> </rule>
回答by rmeador
This is usually handled by your web server directly in the configuration. As you mentioned, the .htaccess file does this for the Apache web server -- it has nothing to do with PHP. Since you're using ASP, it's a near certainty your server is IIS. I know there is a way to set up this direct with IIS, but I don't know what it is. You may be aided in your search by knowing you should be googling for things related to "IIS redirect", not "ASP redirect".
这通常由您的 Web 服务器直接在配置中处理。正如您所提到的,.htaccess 文件为 Apache Web 服务器执行此操作——它与 PHP 无关。由于您使用的是 ASP,因此几乎可以肯定您的服务器是 IIS。我知道有一种方法可以直接使用 IIS 进行设置,但我不知道它是什么。知道您应该在谷歌上搜索与“IIS 重定向”相关的内容,而不是“ASP 重定向”,这可能有助于您进行搜索。
That said, you CAN do it in PHP, and almost certainly ASP as well, but you'll have to have hitting any URL at the wrong domain invoke an ASP script that performs the redirect operation (using appropriate API calls or by setting headers directly). This will necessitate some URL rewriting or somesuch on the part of the server so that all URLs on the wrong host are handled by your script... just do it directly at the server in the first place :)
也就是说,您可以在 PHP 中执行此操作,几乎可以肯定也可以在 ASP 中执行此操作,但是您必须在错误的域中点击任何 URL 来调用执行重定向操作的 ASP 脚本(使用适当的 API 调用或直接设置标头) )。这将需要在服务器端进行一些 URL 重写或类似操作,以便错误主机上的所有 URL 都由您的脚本处理......首先直接在服务器上进行:)
回答by rmeador
We did this on IIS 6 quite simply. We essentially created a second virtual server that had nothing on it than a custom 404 page .aspx page. This page caught any requests for WHATEVERSERVER.com/whateverpage.aspx and redirected to the real server by changing the URL to be www.whateverserver.com/whateverpage.aspx.
我们在 IIS 6 上很简单地做到了这一点。我们基本上创建了第二个虚拟服务器,除了自定义 404 页面 .aspx 页面之外什么都没有。此页面捕获对 WHATEVERSERVER.com/whateverpage.aspx 的任何请求,并通过将 URL 更改为 www.whateverserver.com/whateverpage.aspx 重定向到真实服务器。
Pretty simple to setup, and has the advantage that it will work with any domains that come in to it (if you have multiple domains for instance) without having to setup additional rules for each one. So any requests for www.myoldserver.com/xxx will also get redirected to www.whateverserver.com/xxx
设置起来非常简单,并且它的优势在于它可以与任何进入它的域一起使用(例如,如果您有多个域),而无需为每个域设置额外的规则。因此,对 www.myoldserver.com/xxx 的任何请求也将被重定向到 www.whateverserver.com/xxx
In IIS 7, all this can be done with the URL writing component, but we prefer to keep the redirects off on this virtual server.
在 IIS 7 中,所有这些都可以通过 URL 写入组件完成,但我们更愿意在此虚拟服务器上关闭重定向。
回答by Peter J
The accepted answer works for a single URL or just a few, but my application serves hundreds of domain names (there are far too many URLs to manually enter).
接受的答案适用于单个 URL 或仅几个,但我的应用程序提供数百个域名(手动输入的 URL 太多)。
Here is my IIS7 URL Rewrite Module rule (the action type here is actually a 301 redirect, not a "rewrite"). Works great:
这是我的 IIS7 URL 重写模块规则(这里的操作类型实际上是 301 重定向,而不是“重写”)。效果很好:
<rule name="Add WWW prefix" >
<match url="(.*)" ignoreCase="true" />
<conditions>
<add input="{HTTP_HOST}" negate="true" pattern="^www\.(.+)$" />
</conditions>
<action type="Redirect" url="http://www.{HTTP_HOST}/{R:1}"
appendQueryString="true" redirectType="Permanent" />
</rule>
回答by Elzo Valugi
In order to answer this question, we must first recall the definition of WWW:
为了回答这个问题,我们首先要回顾一下 WWW 的定义:
World Wide Web: n. Abbr. WWW
万维网:n。缩写 万维网
- The complete set of documents residing on all Internet servers that use the HTTP protocol, accessible to users via a simple point-and-click system.
- n : a collection of internet sites that offer text and graphics and sound and animation resources through the hypertext transfer protocol. By default, all popular Web browsers assume the HTTP protocol. In doing so, the software prepends the 'http://' onto the requested URL and automatically connect to the HTTP server on port 80. Why then do many servers require their websites to communicate through the www subdomain? Mail servers do not require you to send emails to [email protected]. Likewise, web servers should allow access to their pages though the main domain unless a particular subdomain is required.
- 驻留在所有使用 HTTP 协议的 Internet 服务器上的完整文档集,用户可通过简单的点击系统访问。
- n :通过超文本传输协议提供文本和图形以及声音和动画资源的互联网站点的集合。默认情况下,所有流行的 Web 浏览器都采用 HTTP 协议。这样做时,软件会在请求的 URL 前面加上“http://”,并自动连接到端口 80 上的 HTTP 服务器。为什么许多服务器要求其网站通过 www 子域进行通信?邮件服务器不需要您将电子邮件发送到收件人@mail.domain.com。同样,除非需要特定的子域,否则 Web 服务器应该允许通过主域访问其页面。
Succinctly, use of the www subdomain is redundant and time consuming to communicate. The internet, media, and society are all better off without it.
简而言之,使用 www 子域进行通信是多余且耗时的。没有它,互联网、媒体和社会都会变得更好。
Using the links at the top of the page, you may view recently validated domains as well as submit domains for real-time validation.
使用页面顶部的链接,您可以查看最近验证的域以及提交域以进行实时验证。
Apache Webserver:
阿帕奇网络服务器:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/ [R=301,L]
Windows Server/IIS:There is no way.
Windows Server/IIS:没有办法。
You can use Url Rewriter from Code Plex. With the same syntax.
您可以使用Code Plex 中的 Url Rewriter。使用相同的语法。
RewriteCond %{HTTP_HOST} !^(www).*$ [NC]
RewriteRule ^(.*)$ http://www.%1 [R=301]
回答by M N Shaukat
In case you are using IIS 7, simply navigate to URL rewrite and add the canonical domain name rule.
如果您使用的是 IIS 7,只需导航到 URL 重写并添加规范域名规则。
P.S. Its to make sure that you get redirected from domain.com to www.domain.com
PS 确保您从 domain.com 重定向到 www.domain.com
回答by Sean
This version will:
此版本将:
- Maintain the http/https of the incoming request.
- Support various hosts in case you need that (e.g. a multi-tenant app that differentiates tenant by domain).
- 维护传入请求的 http/https。
- 如果您需要,支持各种主机(例如,按域区分租户的多租户应用程序)。
<rule name="Redirect to www" stopProcessing="true">
<match url="(.*)" />
<conditions trackAllCaptures="true">
<add input="{CACHE_URL}" pattern="^(.+)://" />
<add input="{HTTP_HOST}" negate="true" pattern="^www\.(.+)$" />
</conditions>
<action type="Redirect" url="{C:1}://www.{HTTP_HOST}/{R:1}" />
</rule>