How do I block direct access to .aspx pages using IIS7's URLRewrite module?
I am using IIS7's URLRewrite feature to hide the .aspx
extension in my ASP.NET WebForms application's URLs.
I'm using the following configuration:
<rule name="WebFormsToMVC" stopProcessing="true">
<match url="^(.*?)\.aspx\?*?.*$" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="{R:1}" />
</rule>`
I can now browse to:
http://www.mytest.com/contact
and this is rewritten to:
http://www.mytest.com/contact.aspx
This preserves 开发者_StackOverflow中文版the "pretty" url in the browser address bar. I have also updated all my links on the site to use the extensionless URLs.
The problem is that the underlying .aspx
pages can still be accessed directly and I'd like to prevent this.
If a user browses to http://www.mytest.com/contact.aspx
I'd like it to either redirect/rewrite to http://www.mytest.com/contact
, or at the very least just return a "Page not found".
Update:
I managed to get this working by redirecting all .aspx
pages to the home directory. This isn't ideal as I'd prefer to send them to the non-.aspx
version, but it will do for now.
<rule name="Block .aspx" stopProcessing="true">
<match url=".aspx" />
<action type="Redirect" url="/" />
</rule>`
How do I rewrite and redirect URLs that directly address .aspx
pages to my friendly URL format?
The following rule will strip the .aspx
from the URL and then redirect the browser to the extensionless URL:
<rule name="Redirect to friendly" stopProcessing="true">
<match url="^(.*)\.aspx$" />
<action type="Redirect" url="{R:1}" />
</rule>
A problem I would foresee with this approach (and with your other rule) is if you have a page called contact.aspx
and a folder named /contact
. This could produce some unexpected problems.
精彩评论