LoginSignup
101
96

More than 5 years have passed since last update.

Nginxのエラーページをカスタマイズする方法

Last updated at Posted at 2015-11-14

Nginxのデフォルトのエラーページは格好良くないし、Nginxを使ってることがバレバレです。それが嫌だったので以下の方法でカスタマイズしました。

基本

Nginxではエラーページのカスタマイズにはerror_pageディレクティブを使います。
カスタマイズの基本的な方法は、custom_404.htmlを作って、nginxの設定ファイルを以下の様な感じにします。
これで、Nginxを再起動して、存在しないファイルへリクエストするとcustom_404.htmlが帰ってくるようになります。

server {

    # 中略

    error_page 404 /custom_404.html;
    location = /custom_404.html {
        root /opt/nginx/html;
        internal;
    }

    # 中略
}

応用

以下では、よりより実践的な例を紹介します。

IP直打ちでのアクセスは全てエラーページを表示

IPアドレスを直接入力してアクセスしてきた場合や想定外のホスト名でアクセスしてきた場合に常にcustom_404.htmlを表示したければ以下の様にします。

server {
    listen 80 default_server;
    error_page 404 /custom_404.html;
    location / {
        return 404;
    }
    location = /custom_404.html {
        root /opt/nginx/html;
        internal;
    }
}

どんなエラーが発生しても404ページを返す

実際に発生しているエラーが403だろうが503だろうが、ユーザーには404エラーが発生しているように見せかけます。
下の例では403, 404, 500, 503のいずれが発生してもクライアントに返すHTTPステータスコードを404に書き換え、custom_404.htmlを返します。

server {
    listen 80;
    server_name example.com;
    error_page 403 404 500 503 =404 /custom_404.html;
    location = /custom_404.html {
        root /opt/nginx/html;
        internal;
    }
}

管理画面を隠す

特定のIP以外から管理画面へアクセスされた時は404画面を出します。
この例では192.168.0.1からの管理画面へのリクエストは許可し、それ以外の場合は404ステータスとcustom_404.htmlを返します。

server {
    listen 80;
    server_name example.com;
    error_page 403 404 =404 /custom_404.html
    location /admin {
       allow 192.168.0.1;
       deny all;  
    }
    location = /custom_404.html {
        root /opt/nginx/html;
        internal;
    }
}

Apacheのエラー画面の真似をする

Nginxを使っていることを隠して、代わりにApacheのフリをするには以下のようにします。

server {
    listen 80;
    server_name example.com;
    error_page 403 404 500 503 = /apache_404.html;
    location = /apache_404.html {
        return 404 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>404 Not Found</title>\n</head><body>\n<h1>Not Found</h1>\n<p>The requested URL $request_uri was not found on this server.</p>\n<hr>\n<address>Apache/2.2.31 Server at $host Port $server_port</address>\n</body></html>";
        internal;
    }
}
101
96
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
101
96