LoginSignup
7
6

More than 5 years have passed since last update.

[nginx] ngx_mruby で html 内の http を https に置換

Last updated at Posted at 2016-06-22

サイトを SSL 化した後で、コンテンツ内の URL を全部 https に置換するのってめんどくさいですよね。
ngx_mruby の mruby_output_filter 使えば一括置換できます。

ssl_filter.rb
# このスクリプトが動くミドルウェアのチェック
if server_name == "NGINX"
  Server = Nginx
elsif server_name == "Apache"
  Server = Apache
end

# アクセスされたホスト名と送信する content type を取得
v = Server::Var.new
host = v.http_host
ctype = v.sent_http_content_type

# content type が text/ ならば http://{サーバ名}/ を https://{サーバ名}/ に置換
if ctype =~ /^text\//
  f = Server::Filter.new
  content = f.body
  f.body = content.gsub /http:\/\/#{host}\//, "https://#{host}/"
end
*.conf
server {
  -- snip --

  location / {
    -- snip --

    # ngx_mruby により text/ 内の http を https に置換
    mruby_output_body_filter /path/to/ssl_filter.rb cache;
  }
}

現行バージョンの ngx_mruby には chunked で送られてくるレスポンスに対するバグがあるので注意

7
6
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
7
6