勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

ホスト側Nginx&コンテナ環境へのBasic認証、リダイレクト、リライト設定方法

  Nginx サーバー

先日コンテナのホスト側をApacheからNginxに変えたが、今度はコンテナ側へのBasic認証・リダイレクト・リライト設定を行いたい。以前にメモした方法で試してみたところ、コンテナ側へのリバースプロキシが必要みたいで正常に動作せず。そのためホスト側Nginx&コンテナ環境での設定方法をメモ。

 

やりたいこと

  • 「/admin/」にアクセスするとBasic認証
  • 「/item/detail/xxx/」にアクセスすると「/item/detail/index.php?id=xxx」にリライト
  • 「/product/」にアクセスするとそれ以降のパスやGETパラメータを引き継いで「/item」にリダイレクト
  • 「/old/old_page.php」にアクセスすると「/new/new_page.php」にリダイレクト

 

環境について

VPS

今回はKAGOYA CLOUD VPSのCPU1コア / メモリ1GBプランで作業した。SSH接続は公式案内の通り以下でログインできる。

  • 接続ポート -> 22
  • ユーザ名 -> root
  • パスワード or 秘密鍵 -> インスタンス作成時に選択したもの

ホスト(VPS)側 AlmaLinux / Nginx

詳細なバージョンは以下の通り。

# AlmaLinuxのバージョン確認
cat /etc/redhat-release

# 実行結果
AlmaLinux release 8.10 (Cerulean Leopard)

# Nginxのバージョン確認
nginx -v

# 実行結果
nginx version: nginx/1.14.1

 

対応方法

Basic認証

サーバにSSH接続し以下の通り進める。

# Apache関連のユーティリティをインストール
dnf install httpd-tools

# パスワードファイルの作成(ユーザー名は適宜変更)
htpasswd -c /etc/nginx/.htpasswd test_user

# 以下の通りパスワードを聞かれるので入力する
New password: 
Re-type new password: 

# 完了すれば以下が表示される
Adding password for user test_user

# カスタム設定ファイルのバックアップ
cp /etc/nginx/conf.d/custom.conf /etc/nginx/conf.d/custom.conf.yyyymmdd

# カスタム設定ファイルの編集
vi /etc/nginx/conf.d/custom.conf

以下をリバースプロキシ設定のserverブロック内に追記する。

# Basic認証
location /admin/ {
    auth_basic "Input your ID and Password.";
    auth_basic_user_file /etc/nginx/.htpasswd;

    proxy_pass http://127.0.0.1:8080;

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

上書き保存し、構文チェック及びNginxのリロードを行うと反映される。

# 構文チェック
nginx -t

# Nginxのリロード
systemctl reload nginx

リライト設定

カスタム設定ファイルをバックアップを取って開く。

# カスタム設定ファイルのバックアップ
cp /etc/nginx/conf.d/custom.conf /etc/nginx/conf.d/custom.conf.yyyymmdd

# カスタム設定ファイルの編集
vi /etc/nginx/conf.d/custom.conf

以下をリバースプロキシ設定のserverブロック内に追記する。

# リライト設定
location /item/detail/ {
    rewrite ^/item/detail/([0-9]+)/$ /item/detail/index.php?id=$1 break;

    proxy_pass http://127.0.0.1:8080;

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

上書き保存し、構文チェック及びNginxのリロードを行うと反映される。

# 構文チェック
nginx -t

# Nginxのリロード
systemctl reload nginx

リダイレクト設定

カスタム設定ファイルをバックアップを取って開く。

# カスタム設定ファイルのバックアップ
cp /etc/nginx/conf.d/custom.conf /etc/nginx/conf.d/custom.conf.yyyymmdd

# カスタム設定ファイルの編集
vi /etc/nginx/conf.d/custom.conf

以下をリバースプロキシ設定のserverブロック内に追記する。ドメイン部分は適宜変更すること。

# productディレクトリをitemディレクトリにリダイレクト
location ~ ^/product/(.*)$ {
    return 301 https://test.com/item/$1$is_args$args;
}

# 個別のリダイレクト
location /old/old_page.php {
    return 301 https://test.com/new/new_page.php;
}

上書き保存し、構文チェック及びNginxのリロードを行うと反映される。

# 構文チェック
nginx -t

# Nginxのリロード
systemctl reload nginx

custom.confサンプル

先日作成したcunstom.confへBasic認証・リライト・リダイレクト全て追加するような場合、以下のような形。

# =========================================================
# IPアドレス直接指定・未定義ドメインのアクセスを拒否
# =========================================================
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    server_name _;

    # SSL証明書の設定
    ssl_certificate     /etc/letsencrypt/live/test.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;

    # レスポンスは何も返さずに接続を拒否
    return 444;
}

# =========================================================
# HTTP -> HTTPSリダイレクト
# =========================================================
server {
    listen 80;
    listen [::]:80;
    server_name test.com www.test.com;

    # すべてHTTPSへ301リダイレクト
    return 301 https://test.com$request_uri;
}

# =========================================================
# 3. wwwあり -> wwwなしへリダイレクト
# =========================================================
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.test.com;

    # SSL証明書の設定
    ssl_certificate     /etc/letsencrypt/live/test.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;

    # wwwなしへ301リダイレクト
    return 301 https://test.com$request_uri;
}

# =========================================================
# コンテナへリバースプロキシ
# =========================================================
server {

    # -----------------------------------------------------
    # 共通設定
    # -----------------------------------------------------

    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name test.com;

    # SSL証明書の設定
    ssl_certificate     /etc/letsencrypt/live/test.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;

    # セキュリティ・TLS設定
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    # クライアントからの最大アップロードサイズ(デフォルト値は1Mと少ないので変更)
    client_max_body_size 20M;

    # ログ設定
    access_log /var/log/nginx/test.com.access.log;
    error_log  /var/log/nginx/test.com.error.log;


    # -----------------------------------------------------
    # 完全一致系の処理
    # -----------------------------------------------------

    # 個別リダイレクト
    location /old/old_page.php {
        return 301 https://test.com/new/new_page.php;
    }


    # -----------------------------------------------------
    # セキュリティ系
    # -----------------------------------------------------

    # Basic認証
    location /admin/ {
        auth_basic "Input your ID and Password.";
        auth_basic_user_file /etc/nginx/.htpasswd;

        proxy_pass http://127.0.0.1:8080;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }


    # -----------------------------------------------------
    # 正規表現を使ったリライト・リダイレクト
    # -----------------------------------------------------

    # productディレクトリをitemディレクトリにリダイレクト
    location ~ ^/product/(.*)$ {
        return 301 https://test.com/item/$1$is_args$args;
    }


    # -----------------------------------------------------
    # その他
    # -----------------------------------------------------

    # リライト設定
    location /item/detail/ {
        rewrite ^/item/detail/([0-9]+)/$ /item/detail/index.php?id=$1 break;

        proxy_pass http://127.0.0.1:8080;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }


    # -----------------------------------------------------
    # 他のどれにも当てはまらない場合
    # -----------------------------------------------------

    # コンテナへのリバースプロキシ設定
    location / {
        proxy_pass http://127.0.0.1:8080;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

 - Nginx サーバー

  関連記事

Podmanで導入したデータベース(MariaDB)用コンテナのチューニングに関する設定方法
Podmanで導入したデータベース(MariaDB)用コンテナのチューニングに関する設定方法

先日Podmanでデータベース(MariaDB)用コンテナを導入したが、当該コン ...

Podmanで導入したapache-phpに各種PHPモジュールを追加する方法
Podmanで導入したapache-phpに各種PHPモジュールを追加する方法

先日Podmanでapache-php8.4を導入したが、phpinfoで確認す ...

CockpitとPodmanでWebサーバ用コンテナを作成しHello Worldページを表示する方法
CockpitとPodmanでWebサーバ用コンテナを作成しHello Worldページを表示する方法

Cockpitにはcockpit-podmanというPodman(Dockerの ...

Podmanで導入したApacheのチューニング(mpm_prefork)に関する設定方法
Podmanで導入したApacheのチューニング(mpm_prefork)に関する設定方法

Podmanで導入したApacheのチューニング(mpm_prefork)を行い ...

Podmanで作成したApache用コンテナにLet's Encryptを導入しHTTPS接続できるようにする方法
Podmanで作成したApache用コンテナにLet's Encryptを導入しHTTPS接続できるようにする方法

先日Podmanで作成したApache用コンテナに対してドメインを割り当てたが、 ...