简体   繁体   中英

URL Rewrite in web.config of IIS to nginx.conf

New to nginx, totally confused.

How to convert this URL rewrite to nginx?

<rewrite>   
    <rules>
        <rule name="IndexFolders" stopProcessing="true">
            <match url="(.*[^/]+)$" />
            <conditions>
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" />
            </conditions>
            <action type="Rewrite" url="/_index/{R:1}.html" />
        </rule>
        <rule name="OtherFile" stopProcessing="true">
            <match url="\.\w+$" />
        </rule>
        <rule name="HtmlFile" stopProcessing="true">
            <match url="^([^.]*[^/]+)$" />
            <action type="Rewrite" url="{R:1}.html" />
        </rule>
    </rules>
</rewrite>

Tried a converter, but not working.

location / {
    if (-d $request_filename){
        set $rule_0 1;
    }
    if ($rule_0 = "1"){
        rewrite /(.*[^/]+)$ /_index/$1.html last;
    }
    location ~* /\.\w+$ {
        break;
    }
    rewrite ^/([^.]*[^/]+)$ /$1.html last;
}

This works in my test environment:

location / {
    if (-d $request_filename){
        rewrite ^/(.*[^/]+)/$ /_index/$1.html break;
    }

    location ~* /.*\.\w+$ {
        break;
    }

    rewrite ^/([^.]*[^/]+)$ /$1.html break;
}            

Notice nginx rewrite directive :

An optional flag parameter can be one of:

last

stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;

break

stops processing the current set of ngx_http_rewrite_module directives as with the break directive;

So if you don't want rewrited URL being searched in a next loop for matching rule, you should use break .

break directive:

Stops processing the current set of ngx_http_rewrite_module directives.

If a directive is specified inside the location, further processing of the request continues in this location.

This is similar to URL Rewriter behaviour:

A rule may have the StopProcessing flag turned on. When this flag is turned on, it means that no more subsequent rules will be processed and the URL produced by this rule will be passed to the IIS request pipeline (if the rule matched). By default, this flag is turned off.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM