返回 404 在 nginx location 块

huangapple go评论62阅读模式
英文:

returning 404 in nginx location block

问题

server{

	include /etc/nginx/mime.types;
	listen 18081;
	root /home/maxou;
	error_page 404 /webserv/error/404.html;

	location \.css
	{
		root /home/maxou/webserv/error;
	}

	location ~ /images {
	return 404;
}

尝试访问以"images/"开头的URI时,我得到了我的自定义404.html错误页面,但没有CSS。我的CSS的GET URI是/images/somefile.css,当然找不到它,因为它位于/webserv/error中。我不明白为什么CSS扩展块没有优先于/images块,因为我没有使用可选修饰符。我做错了什么?如何在/routes/images下返回404代码以及自定义的HTML和CSS?


<details>
<summary>英文:</summary>

server{

include /etc/nginx/mime.types;
listen 18081;
root /home/maxou;
error_page 404 /webserv/error/404.html;

location \.css
{
	root /home/maxou/webserv/error;
}

location ~ /images {
return 404;

}

When I try to access a uri starting with images/ I get my custom 404.html error page but without the css.
The GET uri for my css is /images/somefile.css
and of course dont find it because it is located in /webserv/error.
I dont understand why the css extension block doesnt have the priority on the /images block since I have no optional modifier.
What am I doing wrong ?
How to return a 404 code with my custom html and css with the routes /images ?

</details>


# 答案1
**得分**: 2

您的位置信息不正确
```location \.css```
对于正则表达式位置,您必须使用**~**或**~***修饰符,如下所示:
```location ~* \.css```
&gt; [nginx位置][1]正则表达式是通过前置的“~*”修饰符(用于不区分大小写的匹配)或“~”修饰符(用于区分大小写的&gt;匹配)指定的。

假设*404.html*和*style.css*位于**/var/www/html/custom_errors**中,
*404.html*中的**link**标签:
```&lt;link rel=&quot;stylesheet&quot; href=&quot;custom_errors/style.css&quot;&gt;```
然后配置将类似于:

```error_page 404 /404.html;
location = /404.html{
  root /var/www/html/custom_errors;
  internal;
}
location ~ /images {
  return 404;
}

现在,如果请求http://hostname.tld/images, 您将获得带有您的CSS样式的自定义404错误页面。

英文:

Your location is wrong

location \.css

For regexp location, you must use ~ or ~* modifier, like:

location ~* \.css

>nginx location Regular expressions are specified with the preceding “~*” modifier (for case-insensitive matching), or the “~” modifier (for case-sensitive >matching).

suppose 404.html and style.css locate in /var/www/html/custom_errors,
link tag in 404.html:
&lt;link rel=&quot;stylesheet&quot; href=&quot;custom_errors/style.css&quot;&gt;
then config will be something like:

error_page 404 /404.html;
location = /404.html{
  root /var/www/html/custom_errors;
  internal;
}
location ~ /images {
  return 404;
}

Now if request http://hostname.tld/images, you'll get custom 404 error page with your css style.

huangapple
  • 本文由 发表于 2023年6月6日 03:31:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409491.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定