# 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;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nakamura-shogo.gitbook.io/dev-wiki/apuri/app_nginx.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
