http://example.com/view/tsumugu1515/xxxxxxxx
というURLにアクセスされたときに、内部的には
http://example.com/view/index.php?userid=tsumugu1515&pageid=xxxxxxxx
このようなURLとして処理するには、Apacheでは.htaccessに以下のような内容を記述する。
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)/(.*)$ view/index.php?userid=$1&pageid=$2 [L]
</IfModule>
この記事は上記のような.htaccessをnginxに移植する方法のメモ。パラメータが1つのときの方法はヒットしたが、パラメータ2つはあまりなかったので。
nginx.confに以下のような設定をすることで動いた。
location /view/ {
if ($uri ~* /view/(.*)/(.*)) {
rewrite "^/view/(.*)/(.*)$" /view/index.php?userid=$1&pageid=$2? last;
}
}
全体像はこちら。
nginx.conf
server {
listen 80;
server_name example.com;
root /var/www/html;
location /view/ {
if ($uri ~* /view/(.*)/(.*)) {
rewrite "^/view/(.*)/(.*)$" /view/index.php?userid=$1&pageid=$2? last;
}
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
include fastcgi_params;
}
}
上記の処理のうち
if ($uri ~* /view/(.)/(.)) {
}
このifが非常に大事で、これがないと`http://example.com/view/tsumugu1515`というURLにアクセスされると、PHPファイル(index.php)がそのままダウンロードされてしまった。
また、`rewrite "^/view/(.*)/(.*)$" /view/index.php?userid=$1&pageid=$2? last;`の末尾の`last`を`break`にしてしまうとphp-fpmが実行されず、やはりindex.phpがダウンロードされてしまうので注意。