Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url rewriting rules for static web pages - returning 404 after using url with additional parameters

I use URL Rewriting module for IIS7 - because of URL rewrite for few static files.

Basically I am mapping /pretty-url to /real-file-name.html

So far it is simple.

But after adding query string to pretty url it throws 404 status code. So far I have not found any option to fix this. Any advice, or am I doing something wrong?

Here is the configuration:

<rewriteMaps>
  <rewriteMap name="CoolUrls">
<add key="/pretty-url" value="/real-file.html" />
    ... and so on ...
  </rewriteMap>
</rewriteMaps>

and:

<rules>
  <clear />
    <rule name="Rewrite rule for CoolUrls" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{CoolUrls:{REQUEST_URI}}" pattern="(.+)" />
      </conditions>
      <action type="Rewrite" url="{C:1}" appendQueryString="true" />
    </rule>
</rules>

Any request with query (any parameters after ? mark) ends with 404 status code.

like image 791
Crank Avatar asked Jan 18 '26 12:01

Crank


2 Answers

I assume you want to be able to add a query string and that this query string has to be appended to the rewritten request. You probably don't want the query string to be included in the matching in your rewritemap. Because that's actually what you are doing with {CoolUrls:{REQUEST_URI}} because {REQUEST_URI} also contains the query string. You should replace that with {CoolUrls:{R:0}}.

Complete rule:

<rule name="Rewrite rule for CoolUrls" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{CoolUrls:{R:0}}" pattern="(.+)" />
    </conditions>
    <action type="Rewrite" url="{C:1}" appendQueryString="true" />
</rule>

Update: You should update your rewrite map as {R:0} (the URL) does not include the leading slash from the URL. So your rewrite map should be:

<rewriteMaps>
    <rewriteMap name="CoolUrls">
        <add key="pretty-url" value="/real-file.html" />
        <add key="another/pretty-url" value="/another/real-file.html" />
        ... and so on ...
    </rewriteMap>
</rewriteMaps>
like image 55
Marco Miltenburg Avatar answered Jan 21 '26 06:01

Marco Miltenburg


Another way to do this is by pulling SCRIPT_NAME instead of REQUEST_URI or R:0. It will match the leading slash in your rewriteMap keys too. I left out the advanced and optional config (clear, trackAllCaptures, etc) to serve as a better starting point for others:

<rules>
    <rule name="Rewrite rule for CoolUrls">
      <match url=".*" />
      <conditions>
        <add input="{CoolUrls:{SCRIPT_NAME}}" pattern="(.+)" />
      </conditions>
      <action type="Rewrite" url="{C:1}" appendQueryString="true" />
    </rule>
</rules>
like image 37
twamley Avatar answered Jan 21 '26 08:01

twamley