LoginSignup
5
0

More than 5 years have passed since last update.

nginx+php-fpmでSCRIPT_URxを使う

Last updated at Posted at 2018-12-01

nginx+php-fpm環境で、\$_SERVER['SCRIPT_URI']や\$_SERVER['SCRIPT_URL']が参照できずエラーになる場合の対処法です。
実はこれらのパラメータはPHP標準のものではなくて、RewriteEngineが動いてないと使えないらしいです。

どうするのか

nginxでSCRIPT_URxは使えませんが、似た働きをする変数はあります。
以下の変数を駆使してSCRIPT_URxの値を作り、php-fpmに渡してあげます。

  • $scheme (httpとかhttps)
  • $http_host (ホスト名)
  • $request_uri (/root/foo.php?bar=1みたいなのが入ってる)

値の加工には、ngx_http_map_moduleを使います。(nginxの標準モジュールです。)

map $request_uri $script_url {
    "マッチングルール" "値";
}

上記の例だと、\$request_uriの文字列が "マッチングルール" にマッチした場合、 \$script_urlに"値"が入ります。
複数行書くと、上から順に評価して最初にマッチした行で抜けます。

やってみる

たとえば https://localhost/root/foo.php?bar=1 のようなリクエストに対して、こんな感じのを返したい。

http{}ブロック

/etc/nginx/conf.d/default.conf
map $request_uri $script_url {
    default $request_uri;
    ~^(?<script_filename>.+\.(php))(.*)?$ $script_filename;
    ~^(?<script_filename>.*)(\?.*)$ $script_filename;
    ~^(?<script_filename>.*)(\?.*)?$ $script_filename;
}

\$request_uriの"?"以降の文字列を取り除いて、\$script_urlに入れます。
default valueを指定しているので、何もマッチしなかった場合は$request_uriの値がそのまま入ります。

server{}ブロック

/etc/nginx/conf.d/default.conf
location ~ \.php$ {
    fastcgi_param SCRIPT_URL $script_url;
    fastcgi_param SCRIPT_URI $scheme://$http_host$script_url;
    include fastcgi_params;
}

mapで作った\$script_url, nginx変数の\$scheme, \$http_hostを組合せてSCRIPT_URxを作り、fastcgi_paramにセットします。

元ネタ

Need Apache's SCRIPT_URL equivalent in nginx + php-fpm

5
0
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
5
0