こんにちわ
がじぇったー (@hackmylife7) | Twitter
です。
nginxでエラーページ(カスタム版)
を表示させる方法を記載します。
はじめに
nginxのデフォルトのエラーページは下記のものです。
これだとnginxを使っていることがばればれなので、セキュリティ的にあまりよろしくありません。
また、ユーザーから見て、なにが起こっているのか?何をすれば良いのか?が非常にわかりにくいです。
この記事ではnginxのデフォルトのエラーページではなく、自分で作成したcssやjsをエラーページに反映させて表示する方法を記載します。
設定方法
ディレクトリ構造は下記の様にしています。
自分で作成したhtmlやjs,cssはcustom_pages ディレクトリ配下に配置します。
$ tree -L 3 . ├── conf.d │ └── default.conf ├── html │ └── custom_pages │ ├── 404.html │ ├── 500.html │ ├── css │ ├── images │ └── javascripts └── nginx.conf
nginx.conf は下記の通りです。
nginx.confからconf.d配下のファイルを* で読み込む設定が入っていることがポイントです。
user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; server_tokens off; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; keepalive_timeout 65; include /etc/nginx/conf.d/*.conf; }
default.confを記載します。
server { listen 8082; server_name localhost; real_ip_header X-Forwarded-For; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; location = /server-status { access_log off; stub_status on; } location =/v1/health_check/ { access_log off; return 200; } error_page 404 /404.html; location /404.html { root /etc/nginx/html/custom_pages; } error_page 500 502 503 504 /500.html; location /500.html { root /etc/nginx/html/custom_pages; } location /css { alias /etc/nginx/html/custom_pages/css; } location /images { alias /etc/nginx/html/custom_pages/images; } location /javascripts { alias /etc/nginx/html/custom_pages/javascripts; } } }
設定のポイントを記載していきます。
まずサーバーが404や5xxの httpステータスを返した時、つまりアプリケーションサーバーがダウンしたときにカスタムページが表示されるよう宣言します。
そして、locationディレクティブを使用し、
/404.htmlへのアクセスはどのフォルダーを見にいかせるか、パスを示すためにrootディレクティブを使用します。
error_page 404 /404.html; location /404.html { root /etc/nginx/html/custom_pages; } error_page 500 502 503 504 /500.html; location /500.html { root /etc/nginx/html/custom_pages; }
css やjsは以下の設定が記載されていることにより、読み込んだhtmlファイルからよびだすことが可能です。
location /css { alias /etc/nginx/html/custom_pages/css; }
以上です。