LoginSignup
1
2

More than 1 year has passed since last update.

【Nginx】xxx/xxx.php を任意のURLにリダイレクトさせたときの備忘録

Last updated at Posted at 2022-01-14

はじめに

特定のパスを指定した場合にnginxでリダイレクトさせる処理を追加した際の備忘録です
また、nginx.confの読み方が曖昧だったので以下の記事を参考に整理してみました

やり方

以下を追加する

/nginx/default.conf
    location /hoge/index.php {
        return 301 http://example.com/
    }

設定解説

server {}:バーチャル(仮想)サーバの設定を記述
listen 80;:IP番号とポート番号を指定する
server_name:サーバ名を指定する
root:ドキュメントルートを指定する
add_header:カスタムレスポンスヘッダーを追加する。
X-Frame-Options "SAMEORIGIN";:同じドメイン内のみページの表示を許可する
X-XSS-Protection "1; mode=block";:XSS攻撃を検知してした際に読み込むことを防止する
X-Content-Type-Options "nosniff";:リソースのContent-Typeを無視することがなくなり、HTMLではないものをHTML扱いしてしまうことによるXSSを防ぐ
index:indexファイルを指定する
charset:レスポンスヘッダのContent-typeを指定する
location:パスごと個別のドキュメントルートを設定可能
location /:ルートパスにアクセスされた場合にコンテキスト内の処理を行う
try_files: ファイルが存在するかをチェックする
$uri $uri/:/hogeというファイル名がない場合
$uri/:./hogeというディレクトリを探す
/index.php?$query_string:/index.phpというファイルもなければ内部リダイレクトする
location = /favicon.ico { access_log off; log_not_found off; }:faviconへのアクセスはログへの記録オフ
error_page 404 /index.php;:404エラーが発生したときに内部リダイレクト

/nginx/default.conf
server {
    listen 80;
   
    server_name example.com;
    root /work/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location /hoge/index.php {
        return 301 http://example.com/
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass app:9000;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

さいごに

読んでいただきありがとうございます。
いいねしていただけると記事執筆の励みになりますので、参考になったと思った方は是非よろしくお願いします!

1
2
0

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
1
2