Redirect from page1 to page2, two questions - asp.net

I have a my-site.ru/page1.apsx which will be a part of my-site.ru/page2.aspx so I need to rewrite (or redirect ?) page1.aspx to page2.aspx
I added this to my web.config:
<system.web>
<urlMappings enabled="true">
<add url="~/page1.aspx" mappedUrl="~/page2.aspx"/>
</urlMappings>
</system.web>
The only thing I don't know hot to fix is: why text in address bar is my-site.ru/page1.aspx but i see my-site.ru/page2.aspx ?? I want while redirecting (rewriting) text in address bar changes too.
Question2: How will it reflect on SEO of page1.aspx ? If possible, please, provide a link. i'm a SEO beginner.
PS: I'm not a native english speaker so there must be some errors.

if you are not going to need the content reflected on page1.aspx or if you are going to move the content to your page2.aspx, I would suggest you to do a 301 redirect, which is a a permanent redirect this will affect your seo passing all the SEO information to the page you´re doing the redirect which is page2.aspx in this case.
from the seo perspective other things you can do are:
- remove page1 from your xml sitemap (if you have any)
- Exclude the page from robots.txt
to perform a redirect either you can do it in IIS 7 (or above) you can include an element in your web.config like:
<httpRedirect enabled="true" exactDestination="true" httpResponseStatus="Permanent">
<add wildcard="/page1.aspx" destination="/page2.aspx" />
</httpRedirect>
or you can code the redirection and check for the url in each request like:
public class RedirectHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(this.context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
//check here context.Request for using request object
if(context.Request.FilePath.Contains("page1.aspx"))
{
context.Response.RedirectPermanent("/page2.aspx");
}
}
}
if you are using .NET 4.0 or above take a look to the permament redirection
just be aware that if you perform a regular response.redirect you are doing a 302 redirect that will affect your seo.

on page load
Write this
server.transfer("Page2.aspx")

Related

IIS - How to redirect

How can I redirect www.example.com/foo to www.example.com\subdir\bar.aspx in IIS?
Note: a file called "foo" does not exist. I'd like to just redirect a URL with that pattern to the second URL
The best thing to do is not redirect, but instead use routing to map the URL to the web form. Then you keep a nice clean URL which is easy for users to type, and it looks better for search engines. We can accomplish that with the MapPageRoute method.
Add this to your Global application class (global.asax or global.asax.cs)
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("", "foo", "~/subdir/bar.aspx");
}
Alternatively, you can add this to your web.config to do a redirect.
<configuration>
<location path="foo">
<system.webServer>
<httpRedirect enabled="true" destination="/subdir/bar.aspx" httpResponseStatus="Permanent" />
</system.webServer>
</location>
</configuration>

ASP.NET Web Forms Switch from Site.Mobile.Master

I have an ASP.NET 4.5 Web Forms Application utilizing Bootstrap. http://goo.gl/GZZp9r
I had a problem whereby Site.Mobile.Master was being utilized whenever the website was being rendered in Extra Small ViewPort. Since using Bootstrap I did not need this Site.Mobile.Master.
I had implemented a solution that would cause Site.Mobile.Master to not render, instead only utilizing Site.Master.
public partial class Site_Mobile : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
var AlternateView = "Desktop";
var switchViewRouteName = "AspNet.FriendlyUrls.SwitchView";
var url = GetRouteUrl(switchViewRouteName, new { view = AlternateView, __FriendlyUrls_SwitchViews = true });
url += "?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl);
Response.Redirect(url);
}
}
The above solution is causing problem with GoogleBot because of 302 Redirects.
Someone has indicated that:
"when the user agent is Google mobile when your homepage is requested your site responds with a 302 redirect to
/__FriendlyUrls_SwitchView?ReturnUrl=/
and then the request is 302 redirected again to /
I have read that I cannot simply delete Site.Mobile.Master.
Is there a better solution to NOT render this Site.Mobile.Master for Extra Small ViewPort?
I'm not sure what the benefit would be to use this solution.
But hopefully this would resolve 302 Redirects that is bad for GoogleBot.
<browserCaps>
<result type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<filter>isMobileDevice=false</filter>
</browserCaps>

How to 301 redirect in ASP.NET 4.0?

I am trying to implement URL redirect for the website rather than doing it page by page. I want to do it in the global.asax file. Below is the code i have defined.
I want to have http://website.net as my main url & want to have a permanent URL redirect if someone types in http://www.website.net.
Unfortunately it is not working for the live website. Can anyone point out the problem in the code. The code doesn't generate any error.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
}
}
Main problem: Your're doing the above stuff in Application_Start - which is only executed once. You should hook up with each request. Try this:
void Application_BeginRequest(object sender, EventArgs e)
{
// Code that runs on every request
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
}
}
An even better approach would be to use URL rewriting, which can be configured from within Web.Config:
Microsoft rewriting module - Force www on url Or remove www from url
If using IIS 7 or higher, the simplest solution is to use the httpRedirect element in your web.config.
<httpRedirect enabled="true" exactDestination="true" httpResponseStatus="Permanent">
<add wildcard="/MyOldAspFile.aspx" destination="/MyNewFile.aspx" />
<add wildcard="/MyOldHtmlFile.html" destination="/MyNewFile.aspx" />
</httpRedirect>
This method is very powerful, for example if you have changed the domain but the pages are the same, you have just to add:
<system.webServer>
<httpRedirect enabled="true" childOnly="true" destination="http://www.mynewdomain.com/" />
</system.webServer>
I wrote a small article here: ASP.NET 301 permanent redirects: the best solution
Version 4 of .NET actually has an improved function for single page implementation - the redirectpermanent.
Response.RedirectPermanent(NEW_URL);
Building on previous correct and helpful answers, here are a couple specific examples. Assuming you want to delete the old page (as I did), there are a couple of options.
OPTION 1: Modify the Global.asax
void Application_BeginRequest(object sender, EventArgs e)
{
// Add permanent redirection for retired pages
if (Request.Url.LocalPath.ToLower().StartsWith("/[OLD PAGE NAME]"))
{
Response.RedirectPermanent("/[NEW PAGE NAME]", false);
}
}
OPTION 2: Modify the web.config
<system.webServer>
<httpRedirect enabled="true" httpResponseStatus="Permanent">
<add wildcard="/[OLD PAGE NAME]" destination="/[NEW PAGE NAME]" />
</httpRedirect>
</system.webServer>
if you didn't know what is application domain name ,use something like this
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).Contains("localhost"))return;
var leftPartOfUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).ToLower();
if (leftPartOfUrl.StartsWith("http") && leftPartOfUrl.Split('.').Length == 1)
{
var fullUrl = HttpContext.Current.Request.Url.ToString();
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.StatusCode = 301;
HttpContext.Current.Response.AddHeader("Location", fullUrl.Insert(fullUrl.IndexOf("://", StringComparison.Ordinal) + 3, "www."));
HttpContext.Current.Response.End();
}
}

asp.net page handlers

i want to add some httphandlers for aspx pages by code via a http module.
is that possible? if it is, how?
thanks your advance..
Inherit IHttpModule, override Application_BeginRequest perform your rewrite logic and rewrite the URL with:
private void Application_BeginRequest(Object source, EventArgs e) {
((HttpApplication)source).Context.RewritePath(...);
}
Then register it in web.config with:
<httpModules>
<add name="UrlRewriteHandler" type="namespace.UrlRewriteHandler,project"/>
</httpModules>
Hope that helps.

Determine if user can access the requested page?

I have an ASP.Net website with multiple roles, each with access to a separate directory (i.e. admin users can access /admin, shoppers can access /shop etc), using a shared login page. If someone visits the login page with the return URL set to a directory they do not have access to (e.g. a shopper visits /login.aspx?returnurl=/admin/index.aspx), the user can authentice successfully (the login credentials are valid), but they end up back at the login page (they don't have access to the page they've requested).
How do I pick this up, so I can display a message do the user?
UrlAuthorizationModule.CheckUrlAccessForPrincipal()
is what you need to use to test user access to a location (page or folder) ( http://msdn.microsoft.com/en-us/library/system.web.security.urlauthorizationmodule.checkurlaccessforprincipal.aspx )
I ended up doing this in the page_load event of the login page:
if (User.Identity.IsAuthenticated)
{
LoginErrorDetails.Text = "You are not authorized to view the requested page";
}
The thinking being, if an authenticated user ends up at the login page, they have either been sent their as a result of trying to access an page they are not authorized to view, or they have authenticated and then manually gone to the log in page (unlikely).
A further action would be to send the user to the relevant home page whenever they visit the login page, if they are already authenticated.
One approach would be to override OnLoad of your aspx forms and check if the authenticated user is allowed access to the resource based on the role. So you create a BasePage.cs (in which you define a class BasePage which inherits from System.Web.UI.Page) for example from which all your Forms (aspx) inherit, in which you do this:
protected override void OnLoad(EventArgs e)
{
InitializeSitemap();
if (SiteMap.CurrentNode != null)
{
if (!UrlHelper.IsAnonymousAllowed(SiteMap.CurrentNode) && (!HttpContext.Current.User.Identity.IsAuthenticated || !UrlHelper.IsAccesible(SiteMap.CurrentNode)))
{
// You can redirect here to some form that has a custom message
Response.Redirect("~/Forms/Logout.aspx");
return;
}
}
base.OnLoad(e);
}
Then in your UrlHelper class you need that IsAccessible function used above:
public static bool IsAccesible(SiteMapNode node)
{
bool toRole = false;
foreach (string role in node.Roles)
{
if (role == "*" || HttpContext.Current.User.IsInRole(role))
{
toRole = true;
}
}
return toRole;
}
Here is IsAnonymousAllowed in case you wondered:
public static bool IsAnonymousAllowed(SiteMapNode node)
{
return node[AllowAnonymousAttribute] != null ? bool.Parse(node[AllowAnonymousAttribute]) : false;
}
If you have different directories and you are using asp.net authentication it is very easy.
All you need is to put web.config file in each directory and define roles which can access files in that directory like this:
<authorization>
<allow roles="shoppers"/>
<deny users="?"/>
</authorization>
You can get more details from this article on MSDN
You can set all in main web.config like this:
<!-- Configuration for the "sub1" subdirectory. -->
<location path="sub1">
<system.web>
<httpHandlers>
<add verb="*" path="sub1" type="Type1"/>
<add verb="*" path="sub1" type="Type2"/>
</httpHandlers>
</system.web>
</location>
<!-- Configuration for the "sub1/sub2" subdirectory. -->
<location path="sub1/sub2">
<system.web>
<httpHandlers>
<add verb="*" path="sub1/sub2" type="Type3"/>
<add verb="*" path="sub1/sub2" type="Type4"/>
</httpHandlers>
</system.web>
</location>
</configuration>
This is from this article on MSDN :)
EDIT:
In your page load method do this:
if(!User.IsInRole("shopper"))
{
lblNoAccess.Visible=true;
lnkHome.Url="PATH_TO_HOME_PAGE_OF_THIS_ROLS";
}
Hope this helps you!
You can redirect him on the index page, telling him that he cannot access that page;)
Well, why don't you catch the directory in the login page? If the login page can determine which directory the user is trying to access, maybe they can get redirect to the right page based on role. If someone tries to go to /admin, and authentication succeeds, you can check if they do have access there. If not, you can either redirect to basic landing page indicating they do not have access or you redirect them to the role's landing page.
EDIT:
You could probably do the redirecting in the LoggedIn event of the control.
One other option is to set a session variable when you're checking rights, and displaying that on the login page.
So you could do:
if(!User.IsInRole("shopper"))
{
session("denied") = "You don't have access to shop";
response.redirect("/login");
}
Then in the login page:
if ( session("denied") != "" ) {
message.text = session("denied");
session("denied") = "";
}

Resources