[英]ASP Core: URL Rewrite not working when using AddIISUrlRewrite
I am trying to re-write my URL for the 3 following condition: 1. Remove .php extention 2. Remove .html extention 3. redirect all "www" to non-www 我正在尝试针对以下3种情况重新编写我的URL:1.删除.php扩展名2.删除.html扩展名3.将所有“ www”重定向到非www
I was trying to use the ASP Core's Rewrite package and run the following code: 我试图使用ASP Core的Rewrite包并运行以下代码:
app.UseRewriter(new RewriteOptions().AddIISUrlRewrite(env.WebRootFileProvider, "files/IISUrlRewrite.xml"));
on files/IISUrlRewrite.xml, I have this code: 在文件/IISUrlRewrite.xml上,我有以下代码:
<rewrite>
<rules>
<rule name="RemovePHP">
<match url="^(.*).php$" />
<action type="Rewrite" url="{R:1}" />
</rule>
<rule name="RemoveHTML">
<match url="^(.*).html" />
<action type="Rewrite" url="{R:1}" />
</rule>
<rule name="www to non-www" stopProcessing="true">
<match url="(www.*)" negate="false"></match>
<action type="Redirect" url="http://example.com/{R:1}"></action>
<conditions>
<add input="{HTTP_HOST}" pattern="^example\.com$" negate="true"></add>
</conditions>
</rule>
</rules>
</rewrite>
However, this is not working. 但是,这不起作用。 www's are not being redirected, .php are not being removed.
www不会被重定向,.php不会被删除。 This code works fine when I put it in my web.config file.
当我将其放在web.config文件中时,此代码可以正常工作。
Also, I understand I could do the same thing using the middleware Microsoft Documentation: Url Rewriting 另外,我知道我可以使用中间件Microsoft文档做同样的事情:URL重写
Thank you for the help. 感谢您的帮助。
This usually happens when you add the RewriteMiddleware after configuring the static file handling using the app.UseStaticFiles()
method: if you do that, the RewriteMiddleware might be superseeded by the one in charge of the static files, which could mess up your rewrite rules. 在使用
app.UseStaticFiles()
方法配置静态文件处理后添加RewriteMiddleware时,通常会发生这种情况:如果这样做,则RewriteMiddleware可能会由负责静态文件的人取代,这可能会破坏您的重写规则。
In other words, do not do this: 换句话说, 不要这样做:
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions(...));
app.UseRewriter(new RewriteOptions(...)); // <- MIGHT NOT WORK AS EXPECTED
And do this instead: 而是这样做:
app.UseDefaultFiles();
app.UseRewriter(new RewriteOptions(...)); // <- WORKS
app.UseStaticFiles(new StaticFileOptions(...));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.