Ashish
Ashish

Reputation: 246

Remove Trailing Slash From the URL

I want to redirect "abc.aspx/" to "abc.aspx". How can this be done?

Page gets broken when requested page ends with '/'. How to handle such type of requests? Is there any rewriting rule that can be added into web.config file?

Upvotes: 8

Views: 11599

Answers (2)

must_ache
must_ache

Reputation: 170

I know this is an old post, but Mihai's answer can make your application vulnerable to open redirects attack (see this)

<action type="Redirect" redirectType="Permanent" url="{R:1}" />

This redirect URL can be used for an external redirect, so make sure you have other validations in place before this rule is evaluated or change the redirect to make it internal instead. If you really want to remove the trailing slash and keep it internal, you can change it to:

<action type="Redirect" redirectType="Permanent" url="/{R:1}" />

Cheers

Upvotes: 2

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

In your web.config, under the system.webServer, add

<rewrite>
  <rules>

    <!--To always remove trailing slash from the URL-->
    <rule name="Remove trailing slash" stopProcessing="true">
      <match url="(.*)/$" />
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="{R:1}" />
    </rule>

  </rules>
</rewrite>

Some Gotchas

In your development environment, if you run your web site under Visual Studio Development Sever, you won't be able to see this feature working. You will need to configure your application to run under at least IIS Express.

When you deploy your web site and see that this feature is not working on your production server, it will be because you miss configured something. One of the common mistakes is having overrideModeDefault attribute set to Deny for rules under <sectionGroup name="rewrite"> inside your applicationHost.config file.

If you are on a shared hosting environment and you see that this feature is not working, ask your provider if they have given you the permission of configuring this part.

Source: http://www.tugberkugurlu.com/archive/remove-trailing-slash-from-the-urls-of-your-asp-net-web-site-with-iis-7-url-rewrite-module

Upvotes: 19

Related Questions