StackOverflow like URL Routing

后端 未结 3 1605
离开以前
离开以前 2020-12-14 22:35

Its my understanding that the questions in StackOverflow has the following format

http://stackoverflow.com/questions/{question-id}/{slug-made-from-question-t         


        
3条回答
  •  借酒劲吻你
    2020-12-14 23:15

    This is done via 301 redirect to the preferred canonical URL. The script checks the requested URL to see if the URL matches the "preferred" version of the URL. If not, it sends a 301 redirect to the browser and tells it that the page has permanently moved to this location.

    The reasons for doing this is fairly obvious: Without this, you can construct thousands of URLs like http://stackoverflow.com/questions/6291678/foo, http://stackoverflow.com/questions/6291678/bar, http://stackoverflow.com/questions/6291678/blah; all pointing to same content. Search engines would penalize you for duplicate content.

    Edit

    In your ASP.Net application you can compare the slug provided by the browser against the slug stored in the database. If they do not match, send a 301 redirect. You probably cannot do this via web.config or something else since database in involved. Here is example code I posted on my blog some time ago (not sure if it'll work):

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim myId As Integer = 1234
        Dim mySlug As String = "preferred-slug"
        If Request.Url.AbsolutePath.Equals("/" & myId & "/" & mySlug) = False Then
            Response.Clear()
            Response.Status = "301 Moved Permanently"
            Response.AddHeader("Location", "http://" & Request.Url.Host & "/" & myId & "/" & mySlug & Request.Url.Query)
            Response.End()
        End If
    End Sub
    

    I assume that you've already implemented some form of URL rewriting which throws any request for /\d+/.+ to your asp.net page.

提交回复
热议问题