如何通过重写将基本auth添加到nginx配置中

时间:2013-12-17 04:28:52

标签: nginx basic-authentication http-basic-authentication

我有以下nginx配置我想在此配置中添加基本身份验证。

upstream phpfcgi {
        server 127.0.0.1:7777;
# server unix:/var/run/php5-fpm.sock; #for PHP-FPM running on UNIX socket
}
server{
  listen 80;
  server_name qu.abc.com;
  root /home/qu/website/current/web;
  location / {
# try to serve file directly, fallback to rewrite
          try_files $uri @rewriteapp;

  }

  location @rewriteapp {
  # rewrite all to app.php
          rewrite ^(.*)$ /app.php/$1 last;
  }

  location ~ ^/(app|app_dev|config)\.php(/|$) {
          fastcgi_pass phpfcgi;
          fastcgi_split_path_info ^(.+\.php)(/.*)$;
          include fastcgi_params;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          fastcgi_param HTTPS off;
  }

  error_log /var/log/nginx/project_error.log;
  access_log /var/log/nginx/project_access.log;
}

我已将位置块编辑到此

location / {
# try to serve file directly, fallback to rewrite
          auth_basic "Restricted";
          auth_basic_user_file /home/qu/website/current/web/.htpassword;
          try_files $uri @rewriteapp;

  }

但是这个不能用于重写。 有人可以帮忙吗。

1 个答案:

答案 0 :(得分:2)

听起来我想要为整个服务器启用基本身份验证,而不只是单个locationlocation的工作方式是,一次只应用一个,因此如果您在一个location中指定一个身份验证策略,但它会对其他rewrite执行location }},然后其他location将不受前一个location

的身份验证政策约束

根据auth_basic的文档,似乎不仅可以在location上下文中使用它,还可以在serverhttp中使用它。 / p>

因此,如果您希望整个server要求身份验证,只需将所有auth_basic指令向上移动一级,从单个location移动到单个server {{1}}。