Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS url rewrite | How to remove directory and extension?

I have been struggling with the following for quite some time now:

Default url:

examplesite.com/folder/about.cshtml

Desired url:

examplesite.com/about

Basically I want to accomplish two things:

  • 1 Remove the file extension with realtively compact code.
  • 2 Remove the folder that houses the about page.

I have found some uncommon rules to achieve all the above, but they mostly contain a lot of redundant code that crashes my site when I test it with IIS 8.0.

So I was hoping someone could share a rule that is compact and fits my needs. Or seperate rules with the same outcome.

Every contribution is much appreciated :)

like image 651
Nikita Avatar asked Feb 21 '13 21:02

Nikita


People also ask

How do I fix the URL Rewrite module in IIS?

IIS Rewrite Module ProblemUninstall the Rewrite Module from Windows Features. Go to the Web Platform Installer. Pick Url Rewrite from Products | Server section and install. Restart IIS.

What is the difference between URL Rewrite and redirect?

Simply put, a redirect is a client-side request to have the web browser go to another URL. This means that the URL that you see in the browser will update to the new URL. A rewrite is a server-side rewrite of the URL before it's fully processed by IIS.

How does IIS URL Rewrite work?

The concept of URL rewriting is simple. When a client sends a request to the Web server for a particular URL, the URL rewriting module analyzes the requested URL and changes it to a different URL on the same server.


1 Answers

I'm not certain I entirely understand your needs, but here's something that's at least close. It strips out the first folder and file extension (so examplesite.com/folder/about.cshtml becomes examplesite.com/about and examplesite.com/folder/help/about.cshtml becomes examplesite.com/help/about). If you wanted to strip all folders then just remove the ?.

<rule name="Remove Directory and Extension">
    <match url="^(.*?)/(.*)\.cshtml$" />
    <action type="Rewrite" url="{R:2}" />
</rule>

Update:

Ok, I think what you want is a combination of two rules then:

<rules>
  <rule name="Redirect requests to friendly URLs">
    <match url="^(.*?)/(.*)\.cshtml$" />
    <action type="Redirect" url="{R:2}" />
  </rule>
  <rule name="Rewrite friendly URLs to phsyical paths">
    <match url="^(.*)$" />
    <action type="Rewrite" url="folder/{R:0}.cshtml" />
  </rule>
</rules>

The first rule makes sure that all requests are to friendly URLs. The second takes the friendly URL and rewrites it to your physical path, where the physical path is folder/[FRIENDLY_PATH].cshtml.

like image 180
emjohn Avatar answered Sep 22 '22 03:09

emjohn