5
4

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 5 years have passed since last update.

VirtualBoxでUbunts上のnginxでリバースプロキシしてHTMLを書き換えてHello WorldをCrazy Worldにする

Last updated at Posted at 2019-09-12

はじめに

VirtualBoxでCentOS上のApacheでリバースプロキシしてHTMLを書き換えてHello WorldをCrazy WorldにするのNginxバージョンです。

やったこと

nginxで立ち上げたhttp://localhostにnodeで立ち上げたhttp://localhost:3000/のHTMLを書き換えて表示させる
Screenshot from 2019-08-23 11-30-08.png

nginxの設定

sub_filter '置き換え元文字' "置き換え後文字" ;

nginx.conf
location / {
            # root   html;
            # index  index.html index.htm;
            sub_filter_once off;
            sub_filter 'Hello' 'Crazy' ;
            sub_filter '</head>' "<script>alert('Crazy World')</script></head>" ;
            sub_filter 'nginx' 'Crazy' ;
            proxy_pass   http://127.0.0.1:3000;
        }
/etc/nginx/sites-available/default
location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;
            sub_filter_once off;
            sub_filter 'Hello' 'Crazy' ;
            sub_filter '</head>' "<script>alert('Crazy World')</script></head>" ;
            sub_filter 'nginx' 'Crazy' ;
            proxy_pass   http://127.0.0.1:3000;
        }

nodeで立ち上げるHTMLを準備

hello.html
<!DOCTYPE html>
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>
hello.js
const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  // res.setHeader('Content-Type', 'text/plain');
  // res.end('Hello World!\n');
  fs.readFile('hello.html','UTF-8',
  (error, data)=>{
    res.writeHead(200,{'Content-Type':'text/html'});
    res.write(data);
    res.end();
  });
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

nodeで立ち上げてアクセスhttp://localhost:3000/

aoui@aoui-VirtualBox:/media/sf_reverse_proxy_nginx/nginx/public$ node hello.js
Server running at http://127.0.0.1:3000/

Screenshot from 2019-08-23 11-13-54.png

http://localhostにアクセスしたらHello WorldがCrazy Worldになって表示できた

Screenshot from 2019-08-23 11-14-10.png

ポートが使えない時

他のプロセスがポートを占有してnginxを再起動できない

Dockerでやりたい

docker-composeで立ち上げて、nginxでリバースプロキシしてHTMLを書き換えてHello WorldをCrazy Worldにする

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?