顯示具有 auth_basic 標籤的文章。 顯示所有文章
顯示具有 auth_basic 標籤的文章。 顯示所有文章

2014年1月24日 星期五

[Linux] Nginx 提供 localhost 不受 authorization 限制 @ Ubuntu 12.004

最近用 nginx 架設服務時,採用 HttpAuthBasicModule 限制存取時必須認證才行,然而,偶爾還是希望某些特定 IP 可以不受限制,研究一下是可行的:

http://nginx.org/en/docs/http/ngx_http_core_module.html#satisfy

syntax: satisfy all | any;
default:
satisfy all;
context: http, server, location

Allows access if all (all) or at least one (any) of the ngx_http_access_module, ngx_http_auth_basic_module or ngx_http_auth_request_module modules allow access.


因此,就只需在特定的 location 中,加上上述敘述即可:

location ^~ /service/ {
satisfy any;

# ngx_http_access_module
allow 127.0.0.1/32;
deny all;

# ngx_http_auth_basic_module
auth_basic "Restricted Area";
auth_basic_user_file    htpasswd;

# …
}

2014年1月12日 星期日

[Linux] Nginx + Auth + PHP + CodeIgniter @ Ubuntu 12.04

Nginx Authentication 可以參考官網 HttpAuthBasicModule / ngx_http_auth_basic_module 設定:

location ~^ /ci/  {
  auth_basic            "Restricted";
  auth_basic_user_file  htpasswd;
}


由於 nginx 用 apt-get 安裝,此例 htpasswd 則是位於 /etc/nginx/htpasswd ,若不確定的話,翻一下 nginx access/error logs 來看。

比較特別,如果保護的是一個 location 包含要運行 PHP 程式的話,裡頭需要把完整的 PHP 處理也定義好,據說是因為 nginx auth_basic module 不會繼續往下讀起 nginx.conf。

解法:

location ~^ /ci/  {
  auth_basic            "Restricted";
  auth_basic_user_file  htpasswd;

  # for codeigniter
  index  index.html index.htm index.php;
  try_files $uri $uri/ /ci/index.php;

  # for php
  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

    # With php5-cgi alone:
    fastcgi_pass 127.0.0.1:9000;

    # With php5-fpm:
    #fastcgi_pass unix:/var/run/php5-fpm.sock;

    fastcgi_index index.php;
    include fastcgi_params;
}