1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ディレクトリ形式のURLをGETパラメータ2つのURLに書き換える処理をApacheからnginxへ移植する方法

Posted at

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がダウンロードされてしまうので注意。
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?