> For the complete documentation index, see [llms.txt](https://nakamura-shogo.gitbook.io/dev-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nakamura-shogo.gitbook.io/dev-wiki/apuri/app_nginx.md).

# nginx

## BASIC認証設定

* 簡単に設定できる。
* htpasswdをインストール。

```
$ sudo apt install apache2-utils # Debian系
$ sudo yum install httpd-tools # RedHat系
```

* username/passwordを作成

```
sudo htpasswd -c -b /etc/nginx/.htpasswd {username} {password}
```

* nginx設定ファイルの編集

```
location / {
    auth_basic "Restricted";                   # 認証時に表示されるメッセージ
    auth_basic_user_file /etc/nginx/.htpasswd; # .htpasswdファイルのパス
}
```

* 参考
  * <https://qiita.com/kotarella1110/items/be76b17cdbe61ff7b5ca>
  * <https://qiita.com/You\\_name\\_is\\_YU/items/e8db11eaa10067556e52>

## 自己証明書の設定

* 証明書の作成（作成は別のマシンでもかまわない）

```
openssl req -new -x509 -sha256 -newkey rsa:2048 -days 365 -nodes -out nginx.pem -keyout nginx.key
```

* 適当な場所に複製

```
mkdir -p /etc/nginx/ssl/
cp nginx.key /etc/nginx/ssl/nginx.key
cp nginx.pem /etc/nginx/ssl/nginx.pem
```

* confのどこかに以下のように記述

```
server {
    listen 80;
    return 301 https://$host$request_uri;
}


server {
    listen 443 ssl;
    server_name _;

    ssl_certificate /etc/nginx/ssl/nginx.pem;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
}
```

* 参考
  * <https://qiita.com/inakadegaebal/items/29d21d1f5a904a6ba92d>

## nginxルーティング例

* パスでルーティングする場合はこのようにする。
  * localhost以外に転送することも可能。
  * 下記は別コンテナのmlflowに転送する例。
  * コンテナの場合、コンテナ内のポート番号にすること。

```
server {
    listen 80;
    server_name localhost;

    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
    }

    location /mlflow {
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host http://mlflow:5000/;
        proxy_pass http://mlflow:5000/;
        proxy_redirect off;
    }
}
```

* ポートでルーティングする
  * クライアントからsshでポートフォワーディングする場合は、パスルーティングできない。
  * そういう場合は、別のポートで待ち受け、それを別のサービスにすべて転送すればよい。

```
server {
    listen 5000;
    server_name localhost;

    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    location / {
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host http://mlflow:5000/;
        proxy_pass http://mlflow:5000/;
        proxy_redirect off;
    }
}
```
