大网数据广告活动
网站运营与故障问答

Configure nginx to set the content type from the URL only when there is an allowed user

· 52CE 我爱测

I implemented a location configuration like this ( legituser is set by a map lookup): location / { if ($legituser = 0) { return 200 "you are not allowed to access this url, please do bla bla bla ..."; } more_set_headers "Content-…

问题原文

原帖链接 · Marged · CC BY-SA 4.0

I implemented a location configuration like this (legituser is set by a map lookup):

location / {
  if ($legituser = 0) {
    return 200 "you are not allowed to access this url, please do bla bla bla ...";
  }

  more_set_headers "Content-Type: $arg_mimetype";

  root /media/s3content;
  try_files $uri $uri/ =404;
}

Remark: I know that http status might seem odd in this scenario but I want to make sure the users get proper information and in the real scenario the return contains much more than shown here.

If the user is legit, I want to return files that are stored on S3. The Content-Type needs to be overwritten by the value of ...?mimetype=... which I do by using more_set_headers.

This works quite well, except when I'm not legit and open for example http://server/some/path/somefile?mimetype=image/png. Then I get a png file which consists of only the text sent by return. It became clear to me that return doesn't work like return in a programming language like Java and doesn't exit the location block.

In a programming language I would do something like this:

if( legituser == 0 ) {
  setMimeType( "text/html" );
  return( 200, "you are not ..." );
} else {
  setMimeType( $arg_mimetype );
  try_files ...
}

But this is not how nginx works and I'm absolutely not sure if I'm running into the usual problem if using if in a evil way.

Would this work and be "OK" / proper style ?

set $ct $arg_mimetype;

if( $legituser = 0 ) {
  set $ct 'text/html';
}

more_set_headers "Content-Type: $ct";

if( $legituser = 0 ) {
  return 200 "you are not ...";
}

root /media/s3content;
try_files $uri $uri/ =404;

已采纳解答

原帖链接 · Stephen Ostermiller · CC BY-SA 4.0

From How can I add header conditionally in nginx configuration? on StackOverflow this should be:

map $legituser $mimetypeheadervalue {
    0        'text/html';
    default  $arg_mimetype;
}

location / {

  more_set_headers "Content-Type: $mimetypeheadervalue";

  if ($legituser = 0) {
    return 200 "you are not allowed to access this url, please do bla bla bla ...";
  }

  root /media/s3content;
  try_files $uri $uri/ =404;
}

In the map, if the $legituser is zero it uses text/html and otherwise fills in with the value in your other variable. Then you use the newly created variable from your map to set the header.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2021-08-04)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。