Nginx Rewrite URL Rules Examples
The return directive in server context is very useful in a situation where you have migrated your site to a new domain and you want to redirect all old URLs to the new domain. Further, it also helps in canonicalization of URL by forcing your site to redirect to either www or non-www version.
server {
listen 80;
server_name www.olddomain.com;
return 301 $scheme://www.newdomain.com$request_uri;
}
The return directive in the above server context redirect URL destined to site www.olddomain.com
to www.newdomain.com
. As soon as NGINX receives an URL with www.olddomain.com, it stops processing the page and sends a 301 response code along with rewritten URL to the client. The two variables used in the above return directive are $scheme
and $request_uri
. The variable $scheme
is used to define scheme of the URL (http or https) and the variable $request_uri
contains complete URI with parameters if any. Remember both the variable fetches this information from input URL while rewriting the URL.
server_name
Server names
server {
listen 80;
server_name example.org www.example.org;
…
}
server {
listen 80;
server_name *.example.org;
…
}
server {
listen 80;
server_name mail.*;
…
}
server {
listen 80;
server_name ~^(?.+).example.net$;
…
}
旧ドメインから新ドメインへのリダイレクト
旧ドメインがSSL対応だった場合のリダイレクト設定(プロキシサーバー)
注) 旧ドメインのSSL認証は必要ありません。
/etc/nginx/conf.d/redirect_to_xxx.conf
server {
server_name old.example.com;
return 301 https://new.example.com$request_uri;
listen 443;
listen [::]:443;
#ssl_certificate .../old.example.com/fullchain.pem;
#ssl_certificate_key .../old.example.com/privkey.pem;
#include .../options-ssl-nginx.conf;
#ssl_dhparam .../dhparam.pem;
}
server {
if ($host = old.example.com) {
return 301 https://new.example.com$request_uri;
}
server_name old.example.com;
listen 80;
listen [::]:80;
return 404;
}
Nginxセキュリティ設定追加
server {
.....
# Set CSP
# Please note that CSP are very tricky and can be quite advanced to get right
# For most optimal security however they are absolutely mandatory
# There are ways to 'override' them for easier development
# However they should be carefully evaluated, defined and included
add_header Content-Security-Policy "default-src 'self';" always;
add_header Access-Control-Allow-Origin "example.com";
# Referrer Policy
add_header Referrer-Policy origin;
.....
}
HTTP/2
/etc/nginx/conf.d/default.conf
server {
...
add_header Strict-Transport-Security "max-age=15768000" always;
...
...
listen [::]:443 ssl http2 ipv6only=on;
listen 443 ssl http2;
...
}
/etc/letsencrypt/options-ssl-nginx.conf
...
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
OCSP (Online Certificate Status Protocol) Stapling
What is OCSP Stapling?
OSCS とは、クライアントが使用するブラウザがHTTPSのURLへアクセスする際、SSL証明書が失効していないかどうか発行元のCAに直接アクセスして確認する手順です。
OCSP Stapling は、デジタル署名およびタイムスタンプが付けられたバージョンの OCSP 応答をウェブサーバー上に直接配置することにより、パフォーマンスを向上させます。 このステープルされた OCSP 応答は、CA によって設定された事前定義された間隔で更新されます。 ステープル留めされた OCSP 応答により、Web サーバーは最初の SSL ハンドシェイク内に OCSP 応答を含めることができ、ユーザーが CA への別の外部接続を行う必要はありません。
ルートCAと中間証明書を使用してOCSP応答の信頼チェーンを取得(Letsencrypt)
# curl https://letsencrypt.org/certs/isrgrootx1.pem.txt > /etc/ssl/letsencrypt.cot.pem \
&& curl https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem.txt >> /etc/ssl/letsencrypt.cot.pem \
&& curl https://letsencrypt.org/certs/letsencryptauthorityx3.pem.txt >> /etc/ssl/letsencrypt.cot.pem \
&& chown root:ssl-cert /etc/ssl/letsencrypt.cot.pem && chmod 644 /etc/ssl/letsencrypt.cot.pem
取得した信頼チェーンをNginxで指定
/etc/nginx/conf.d/default.conf
.....
# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/ssl/letsencrypt.cot.pem;
.....
Rate Limiting with NGINX
レート制限は、ブルートフォースによるパスワード推測攻撃を遅らせるなどのセキュリティ目的で使用されます。
https://blog.nginx.org/blog/rate-limiting-nginx
/etc/nginx/conf.d/rate_limit.conf
limit_req_zone $binary_remote_addr zone=rate_limit:10m rate=10r/s;
limit_req_status 429;
/etc/nginx/conf.d/xxx.conf
location /login/ {
limit_req zone=mylimit burst=20 nodelay;
.....
.....
}
Docker Nginx + Logrotate
ホストマシンのlogrotateデーモンを利用してDocker Nginxのログファイルを更新するため、コンテナの/var/log/nginx
フォルダをホストマシンと共有。
nginxのボリュームセクションに以下を追加
docker-compose.yml
volumes:
......
......
# for fail2ban settings and logrotate, share log files between host and docker nginx container
- ./container_logs/nginx:/var/log/nginx
......
......
logrotateのnginx設定ファイルを新規作成
/etc/logrotate.d/nginx
/xxx/xxx/container_logs/nginx/*.log { #---> ホストマシン上での共有ファイルまでのフルパス
daily
missingok
rotate 31
dateext
compress
delaycompress
notifempty
sharedscripts
postrotate
cd /xxx/xxx/xxx \ #---> docker-compose.ymlファイルが格納されているディレクトリ
&& docker compose -p project1 kill -s USR1 nginx
endscript
}
注) Docker Composeをプロジェクト名を付加して稼働したため、-p project1
を追加
動作確認
$ sudo logrotate -f /etc/logrotate.d/nginx
[+] Killing 1/1
✔ Container nginx Killed