Home
Packages
Forums
Wiki
GitLab
Security
AUR
Download
コンテンツにスキップ
メインメニュー
メインメニュー
サイドバーに移動
非表示
案内
メインページ
目次
コミュニティに貢献
最近の出来事
おまかせ表示
特別ページ
交流
ヘルプ
貢献
最近の更新
最近の議論
新しいページ
統計
リクエスト
ArchWiki
検索
検索
表示
アカウント作成
ログイン
個人用ツール
アカウント作成
ログイン
Nginxのソースを表示
ページ
議論
日本語
閲覧
ソースを閲覧
履歴を表示
ツール
ツール
サイドバーに移動
非表示
操作
閲覧
ソースを閲覧
履歴を表示
全般
リンク元
関連ページの更新状況
ページ情報
表示
サイドバーに移動
非表示
←
Nginx
あなたには「このページの編集」を行う権限がありません。理由は以下の通りです:
この操作は、次のグループに属する利用者のみが実行できます:
登録利用者
。
このページのソースの閲覧やコピーができます。
{{Lowercase title}} [[Category:ウェブサーバー]] [[de:Nginx]] [[en:Nginx]] [[ru:Nginx]] [[zh-hans:Nginx]] [[Wikipedia:ja:nginx|nginx]] ("エンジンエックス"と発音します)は 2005 年から Igor Sysoev(ロシア)によって開発されている、フリーでオープンソースかつハイパフォーマンスな HTTP サーバーかつリバースプロクシで、IMAP/POP3 プロクシサーバーとしても機能します。Nginx は主に、その安定性・多機能・単純な設定・低リソース消費によって知られています。 この記事では nginx の設定方法と、[[#FastCGI]] を使って [[PHP]] と統合する方法を説明します。 == インストール == [[公式リポジトリ]]から {{Pkg|nginx-mainline}} (メインラインブランチ: 最新の機能・アップデート・修正) か {{Pkg|nginx}} (安定ブランチ: 重要な修正のみを適応) のどちらかを[[Pacman|インストール]]できます。 {{Note| 基本的には[https://www.nginx.com/blog/nginx-1-6-1-7-released/ 最新版の利用が推奨されています]が、 * サードパーティ製のモジュールとの互換性 * 新規に追加された機能の未知のバグ などによる影響が懸念される場合は、安定版を使用することを検討してください。 }} ''Ruby on Rails'' のためにインストールするには、[[Ruby on Rails#Rails パーフェクトセットアップ]]を参照してください。 セキュリティを向上させるために chroot によるインストールをするには、[[#chroot でインストール]] を参照してください。 == サービスの開始 == {{ic|nginx.service}} を[[起動/有効化]]します。 http://127.0.0.1 で提供されるデフォルトのページは、{{ic|/usr/share/nginx/html/index.html}} です。 == 設定 == nginx における最初の手順は [http://nginx.org/en/docs/beginners_guide.html 公式のビギナーズガイド] で説明されています。{{ic|/etc/nginx/}} にあるファイルを編集することで Nginx の設定ができます。メインの設定ファイルは {{ic|/etc/nginx/nginx.conf}} です。 より詳しい解説は、公式の [http://nginx.org/en/docs/ ドキュメント] にある [http://wiki.nginx.org/Configuration Nginx Configuration Examples] にあります。 以下の例は、最も一般的な使用例をカバーしています。ここでは、ドキュメントのデフォルトの場所 ({{ic|/usr/share/nginx/html}}) を使用することを想定しています。そうでない場合は、代わりにあなたのパスを指定してください。 {{Tip|DigitalOcean から [https://nginxconfig.io/ Nginx configuration tool] が提供されています。}} === 設定例 === {{hc|/etc/nginx/nginx.conf|<nowiki> user http; worker_processes auto; worker_cpu_affinity auto; events { multi_accept on; worker_connections 1024; } http { charset utf-8; sendfile on; tcp_nopush on; tcp_nodelay on; server_tokens off; log_not_found off; types_hash_max_size 4096; client_max_body_size 16M; # MIME include mime.types; default_type application/octet-stream; # logging access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log warn; # load configs include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } </nowiki>}} === 一般設定 === ==== プロセス数とコネクション数 ==== {{ic|worker_processes}} の適当な値を探って下さい。この設定は最終的に nginx が受け入れる接続の数と利用できるプロセスの数を定義します。通常、システムのハードウェアのスレッド数にすると良いでしょう。また、バージョン 1.3.8 と 1.2.5 から {{ic|worker_processes}} には {{ic|auto}} と設定することができ、最適な値を自動的に検出します ([http://nginx.org/en/docs/ngx_core_module.html#worker_processes ソース])。 nginx が受け入れる最大接続数は {{ic|1=max_clients = worker_processes * worker_connections}} で計算できます。 ==== 別のユーザーで実行する ==== デフォルトでは、{{Pkg|nginx}} はマスタープロセスを {{ic|root}} で、ワーカープロセスを {{ic|http}} ユーザで実行します。ワーカープロセスを別のユーザで実行するには、{{ic|nginx.conf}} の {{ic|user}} ディレクティブを変更します。 {{hc|/etc/nginx/nginx.conf| user ''user'' [''group'']; }} group が省略された場合は、''user'' と同じ名前のグループが使用されます。 {{Tip|1=[[systemd]] を使って {{ic|root}} で何もせずに nginx を動かすことも可能です。[[#systemd を使って非特権で動作させる]]を参照してください。}} ==== サーバーブロック ==== {{ic|server}} ブロックを使うことで複数のドメインを利用することができます。"バーチャルホスト"とも呼ばれますが、これは [[Apache]] の用語です。{{ic|server}} ブロックの利用方法は [http://wiki.nginx.org/ServerBlockExample Apache] とは異なっています。[https://www.nginx.com/resources/wiki/start/topics/examples/server_blocks/ upstream examples] も参照してください。 以下の例では2つのドメインの接続をサーバーが待機します: {{ic|domainname1.dom}} と {{ic|domainname2.dom}}: {{hc|/etc/nginx/nginx.conf|<nowiki> ... server { listen 80; server_name domainname1.dom; root /usr/share/nginx/domainname1.dom/html; location / { index index.php index.html index.htm; } } server { listen 80; server_name domainname2.dom; root /usr/share/nginx/domainname2.dom/html; ... } ... }</nowiki>}} {{ic|nginx.service}} を[[再起動]]して変更を適用します。 クライアントからの接続時にこれらのドメイン名を解決するには、[[BIND]] や [[dnsmasq]] などのDNSサーバーを設定する必要があります。 ローカルマシンでバーチャルホストをテストするには、{{ic|/etc/hosts}} ファイルにバーチャルネームを追加してください: 127.0.0.1 domainname1.dom 127.0.0.1 domainname2.dom ===== サーバーエントリの管理 ===== 異なる {{ic|server}} ブロックを異なるファイルに配置することができます。これにより、特定のサイトを簡単に有効または無効にできます。 次のディレクトリを作成します。 # mkdir /etc/nginx/sites-available # mkdir /etc/nginx/sites-enabled {{ic|sites-available}} ディレクトリに、一つ以上のサーバーブロックを含むファイルを作成します。 {{hc|/etc/nginx/sites-available/example.conf|<nowiki> server { listen 443 ssl http2; listen [::]:443 ssl http2; ... } </nowiki>}} {{ic|http}} ブロックの最後に、{{ic|include sites-enabled/*;}} を追加します。 {{hc|/etc/nginx/nginx.conf|<nowiki> http { ... include sites-enabled/*; } </nowiki>}} サイトを有効にするには、シンボリックリンクを作成するだけです。 # ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/example.conf サイトを無効にするには、アクティブなシンボリックリンクのリンクを解除します。 # unlink /etc/nginx/sites-enabled/example.conf {{ic|nginx.service}} を [[リロード]]/[[再起動]] して、サイト設定の変更を有効にします。 ==== TLS ==== [[OpenSSL]] は TLS をサポートし、Arch のインストール時にデフォルトでインストールされます。 {{Tip| * SSL を設定する前に [http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate ngx_http_ssl_module] のドキュメントを読むことを推奨します。 * [[Let’s Encrypt]] は無料の、自動化されたオープンな証明局です。コマンドラインおよび自動設定から直接有効な SSL 証明書を要求するプラグインを利用可能です。 * Mozilla has a useful [[MozillaWiki:Security/Server Side TLS|TLS article]] as well as an [https://mozilla.github.io/server-side-tls/ssl-config-generator/ automated tool] to help create a more secure configuration. }} {{Warning|If you plan on implementing SSL/TLS, know that some variations and implementations are [https://weakdh.org/#affected still] [[wikipedia:Transport_Layer_Security#Attacks_against_TLS.2FSSL|vulnerable to attack]]. For details on these current vulnerabilities within SSL/TLS and how to apply appropriate changes to nginx, visit http://disablessl3.com/ and https://weakdh.org/sysadmin.html}} Create a private key and self-signed certificate. This is adequate for most installations that do not require a [[OpenSSL#Generate a certificate signing request|CSR]]: # mkdir /etc/nginx/ssl # cd /etc/nginx/ssl # openssl req -new -x509 -nodes -newkey rsa:4096 -keyout server.key -out server.crt -days 1095 # chmod 400 server.key # chmod 444 server.crt {{Note|The {{ic|-days}} switch is optional and RSA keysize can be as low as 2048 (default).}} If you need to create a CSR, follow these instructions instead of the above: # mkdir /etc/nginx/ssl # cd /etc/nginx/ssl # openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out server.key # chmod 400 server.key # openssl req -new -sha256 -key server.key -out server.csr # openssl x509 -req -days 1095 -in server.csr -signkey server.key -out server.crt {{Note|For more ''openssl'' options, read its man page {{man|1ssl|openssl}} or peruse its [https://www.openssl.org/docs/ extensive documentation].}} A starting point for a {{ic|/etc/nginx/nginx.conf}} with TLS is [https://ssl-config.mozilla.org/#server=nginx Mozilla's SSL Configuration Generator]. {{ic|nginx.service}} を[[再起動]] して変更内容を反映させます。 ==== Per-user directories ==== To replicate Apache-style {{ic|~user}} URLs to users' {{ic|~/public_html}} directories, try the following. (Note: if both rules are used, below, the more-specific PHP rule must come first.) {{hc|/etc/nginx/nginx.conf|<nowiki> ... server { ... # PHP in user directories, e.g. http://example.com/~user/test.php location ~ ^/~(.+?)(/.+\.php)$ { alias /home/$1/public_html$2; fastcgi_pass unix:/run/php-fpm/php-fpm.sock; fastcgi_index index.php; include fastcgi.conf; } # User directories, e.g. http://example.com/~user/ location ~ ^/~(.+?)(/.*)?$ { alias /home/$1/public_html$2; index index.html index.htm; autoindex on; } ... } ... </nowiki>}} See [[#PHP implementation]] for more information on PHP configuration with {{ic|nginx}}. {{ic|nginx.service}} を[[再起動]] して新しい設定を有効にします。 === FastCGI === FastCGI、または FCGI はウェブサーバーでインタラクティブなプログラムを動作させるためのプロトコルです。FastCGI は Common Gateway Interface (CGI) の変種で、ウェブサーバーと CGI プログラムのオーバーヘッドを減らすよう設計されていて、サーバーはより多くのウェブページのリクエストを一度に捌くことができます。 Nginx には FastCGI が組み込まれており多くの外部ツールが動きます、例えば Perl、[[PHP]]、[[Python]] など。これらを使うためにはまず FastCGI サーバーを動かす必要があります。 ==== PHP を動かす ==== PHP のために FastCGI サーバーを動かす方法は複数あります。ここでは推奨方法として php-fpm を使う方法を記載しています。 ===== 手順1: PHP の設定 ===== {{Pkg|php}} をインストールしてください。{{ic|/etc/php/php.ini}} の中にある {{Ic|open_basedir}} に PHP ファイルが含まれているベースディレクトリを ({{ic|/srv/http/}} や {{ic|/usr/share/webapps/}} のような感じで)指定しなくてはなりません: open_basedir = /usr/share/webapps/:/srv/http/:/home/:/tmp/:/usr/share/pear/ そうしたら必要なモジュールを設定しましょう。例えば sqlite3 を使うなら {{Pkg|php-sqlite}} をインストールして、{{ic|/etc/php/php.ini}} の次の行をアンコメントして有効にします: extension=sqlite3.so {{Note|chroot 環境で nginx を動かしている場合 (chroot は {{ic|/srv/nginx-jail}} で、ウェブページは {{ic|/srv/nginx-jail/www}}) です。{{ic|/etc/php/php-fpm.conf}} ファイルを編集して {{ic|chroot /srv/nginx-jail}} と {{ic|1=listen = /srv/nginx-jail/run/php-fpm/php-fpm.sock}} ディレクティブを pool セクション (デフォルトは {{ic|[www]}}) の中に記述する必要があります。ソケットファイルのディレクトリが存在しない場合は作成してください。}} ====== MariaDB ====== [[MariaDB]] で説明されているようにして MySQL/MariaDB を設定してください。 {{ic|/etc/php/php.ini}} の以下の行の [http://www.php.net/manual/en/mysqlinfo.api.choosing.php 少なくともどれか一つ] をアンコメント: extension=pdo_mysql.so extension=mysqli.so {{Warning|PHP 5.5 から、{{ic|mysql.so}} は [http://www.php.net/manual/de/migration55.deprecated.php 廃止] されログファイルにエラーが表示されます。}} ウェブスクリプトのために最小権限の MySQL ユーザーを追加することができます。また、{{ic|/etc/mysql/my.cnf}} を編集して {{ic|skip-networking}} 行をアンコメントすると MySQL サーバーはローカルホストからしかアクセスできなくなります。変更を適用するには MySQL を再起動する必要があります。 {{Tip|データベースを利用するために [[phpMyAdmin]], [[Adminer]], {{Pkg|mysql-workbench}} などのツールをインストールしても良いでしょう。}} ===== 手順2: php-fpm ===== * http://php-fpm.org {{Pkg|php-fpm}} をインストールします: # pacman -S php-fpm 設定ファイルは {{ic|/etc/php/php-fpm.conf}} です。 サービスを動かします: # systemctl start php-fpm {{Ic|php-fpm}} をスタートアップ時に有効にします: # systemctl enable php-fpm.service ===== 手順3: Nginx の設定 ===== それぞれの {{ic|server}} ブロックの中の {{ic|location}} ブロックに PHP アプリケーションを次のように記述します: location ~ \.php$ { fastcgi_pass unix:/run/php-fpm/php-fpm.sock; fastcgi_index index.php; include fastcgi.conf; } {{Ic|/etc/nginx/php.conf}} を作って設定をそこに書く場合、このファイルを {{Ic|server}} ブロックに入れて下さい。 server = { ... include php.conf; ... } .html や .htm ファイルを PHP として処理したい場合は、以下のようにしてください: location ~ \.(php'''|html|htm''')$ { fastcgi_pass unix:/run/php-fpm/php-fpm.sock; fastcgi_index index.php; include fastcgi.conf; } 拡張子が .php でないファイルを php-fpm で動かすことを {{Ic|/etc/php/php-fpm.conf}} で有効にする必要があります: security.limit_extensions = .php .html .htm 設定を変えた後は php-fpm デーモンを再起動してください。 # systemctl restart php-fpm {{Note|{{Ic|fastcgi_pass}} 引数に'''注意を払って下さい'''、FastCGI サーバーの設定ファイルで定義された TCP や Unix ソケットでなくてはなりません。'''デフォルトの''' {{Ic|php-fpm}} (Unix) ソケットは fastcgi_pass unix:/run/php-fpm/php-fpm.sock; '''デフォルトの代わりに'''、通常の TCP ソケットを使うこともできます fastcgi_pass 127.0.0.1:9000; ただし Unix ドメインソケットの方が高速です。}} Nginx のための FastCGI 設定がある {{Ic|fastcgi.conf}} か {{Ic|fastcgi_params}} が含まれていますが、後者は使われなくなりました。これらのファイルは Nginx をインストールしたときに作られます。 最後に、Nginx が動作している場合は再起動してください: # systemctl restart nginx FastCGI をテストしたい場合は、{{ic|/usr/share/nginx/html/index.php}} を次の内容で作成して <?php phpinfo(); ?> ブラウザで http://127.0.0.1/index.php を開いて下さい。 以下は実際の設定例です。例の中では {{ic|root}} パスは {{ic|server}} の下に直接指定されており (デフォルト設定のように) {{ic|location}} の中には置いていません。 server { listen 80; server_name localhost; root /usr/share/nginx/html; location / { index index.html index.htm index.php; } location ~ \.php$ { #fastcgi_pass 127.0.0.1:9000; (depending on your php-fpm socket configuration) fastcgi_pass unix:/run/php-fpm/php-fpm.sock; fastcgi_index index.php; include fastcgi.conf; } } ==== CGI を動かす ==== この実装は CGI アプリケーションに必要です。 ===== 手順1: fcgiwrap ===== {{Pkg|fcgiwrap}} をインストールしてください。 設定ファイルは {{ic|/usr/lib/systemd/system/fcgiwrap.socket}} です。 [[systemd]] の ''fcgiwrap.socket'' を有効化・起動します。 この systemd ユニットファイルは現在 [https://bugs.archlinux.org/task/31696 ArchLinux のタスクページ]で議論されています。思い通りに動くか確認するためにユニットファイルを自分で検査すると良いでしょう。 ====== マルチワーカースレッド ====== 複数のワーカースレッドを生成したい場合は、{{AUR|multiwatch}} を使用するのが推奨されています。これはクラッシュした子スレッドの再起動の面倒をみてくれます。multiwatch は systemd が作成したソケットを管理できないため、unix ソケットを作成するには {{ic|spawn-fcgi}} を使う必要がありますが、ユニットファイルから直接実行した場合は fcgiwrap には問題が生じません。 {{ic|/usr/lib/systemd/system/fcgiwrap.service}} から {{ic|/etc/systemd/system/fcgiwrap.service}} にユニットファイルをコピーして (存在する場合は {{ic|fcgiwrap.socket}} ユニットも)、{{ic|ExecStart}} 行を必要に応じて修正してください。以下は {{AUR|multiwatch}} を使用するユニットファイルです。{{ic|fcgiwrap.socket}} が実行中だったり有効になっていないことを確認してください、このユニットと衝突してしまうからです: {{hc|/etc/systemd/system/fcgiwrap.service|2= [Unit] Description=Simple CGI Server After=nss-user-lookup.target [Service] ExecStartPre=/bin/rm -f /run/fcgiwrap.socket ExecStart=/usr/bin/spawn-fcgi -u http -g http -s /run/fcgiwrap.sock -n -- /usr/bin/multiwatch -f 10 -- /usr/sbin/fcgiwrap ExecStartPost=/usr/bin/chmod 660 /run/fcgiwrap.sock PrivateTmp=true Restart=on-failure [Install] WantedBy=multi-user.target }} {{ic|-f 10}} は生成する子スレッドの数に変更してください。 {{Warning|The ExecStartPost line is required because of strange behaviour I'm seeing when I use the {{ic|-M 660}} option for {{ic|spawn-fcgi}}. The wrong mode is set. This may be a bug?}} ===== 手順2: Nginx の設定 ===== CGI ウェブアプリケーションを置くそれぞれの {{Ic|server}} ブロックには以下のような {{Ic|location}} ブロックを記述します: location ~ \.cgi$ { root /path/to/server/cgi-bin; fastcgi_pass unix:/run/fcgiwrap.sock; include fastcgi.conf; } {{Ic|fcgiwrap}} の'''デフォルト''' (Unix) ソケットは ''/run/fcgiwrap.sock'' です。 == chroot でインストール == [[chroot]] に Nginx をインストールすることでセキュリティレイヤーを追加することができます。セキュリティを最大限に高めるために、Nginx サーバーを動かすのに必要なファイルだけを入れて、全てのファイルは出来る限り最小限の権限にします。例えば、なるべく root が所有するようにして、{{ic|/usr/bin}} などのディレクトリは読み書きできないようにするなど。 Arch はデフォルトでサーバーを実行するための {{ic|http}} ユーザーとグループが設定されています。chroot は {{ic|/srv/http}} で動作させます。 この牢獄を作るための perl スクリプトが [https://gist.github.com/4365696 jail.pl gist] にあります。このスクリプトを使用するか、またはこの記事の指示に従って作成するか選ぶことができます。スクリプトは root で実行してください。変更を適用する前に行をアンコメントする必要があります。 === 必要なデバイスを作成 === Nginx には {{ic|/dev/null}}, {{ic|/dev/random}}, {{ic|/dev/urandom}} が必要です。これらを chroot にインストールするために {{ic|/dev/}} フォルダを作成してデバイスを mknod で追加します。chroot が危険になったときでも、攻撃者が {{ic|/dev/sda1}} などの重要なデバイスにアクセスするには chroot から脱出しなくてはならないようにするために、{{ic|/dev/}} を全てマウントはしません。 {{Tip|mknod の引数については {{ic|man mknod}} や {{ic|<nowiki>ls -l /dev/{null,random,urandom}</nowiki>}} を見て下さい。}} # export JAIL=/srv/http # mkdir $JAIL/dev # mknod -m 0666 $JAIL/dev/null c 1 3 # mknod -m 0666 $JAIL/dev/random c 1 8 # mknod -m 0444 $JAIL/dev/urandom c 1 9 === 必要なフォルダを作成 === Nginx を適切に実行するためにはたくさんのファイルが必要になります。それらをコピーする前に、ファイルを保存するためのフォルダを作成してください。ここでは Nginx のドキュメントルートが {{ic|/srv/http/www}} であると仮定します。 # mkdir -p $JAIL/etc/nginx/logs # mkdir -p $JAIL/usr/{lib,bin} # mkdir -p $JAIL/usr/share/nginx # mkdir -p $JAIL/var/{log,lib}/nginx # mkdir -p $JAIL/www/cgi-bin # mkdir -p $JAIL/{run,tmp} # cd $JAIL; ln -s usr/lib lib {{Note|64ビットのカーネルを使っている場合 {{ic|usr/lib}} に {{ic|lib64}} と {{ic|usr/lib64}} のシンボリックリンクを作成する必要があります: {{ic|cd $JAIL; ln -s usr/lib lib64}} と {{ic|cd $JAIL/usr; ln -s lib lib64}}。}} そして {{ic|$JAIL/tmp}} と {{ic|$JAIL/run}} を tmpfs でマウントします。攻撃者が RAM を全て喰いつくせないようにサイズを制限すると良いでしょう。 # mount -t tmpfs none $JAIL/run -o 'noexec,size=1M' # mount -t tmpfs none $JAIL/tmp -o 'noexec,size=100M' 再起動してもマウントが維持されるように、以下のエントリを {{ic|/etc/fstab}} に追加します: {{hc|/etc/fstab|<nowiki> tmpfs /srv/http/run tmpfs rw,noexec,relatime,size=1024k 0 0 tmpfs /srv/http/tmp tmpfs rw,noexec,relatime,size=102400k 0 0 </nowiki>}} === chroot に移住 === まず平易なファイルをコピーします。 # cp -r /usr/share/nginx/* $JAIL/usr/share/nginx # cp -r /usr/share/nginx/html/* $JAIL/www # cp /usr/bin/nginx $JAIL/usr/bin/ # cp -r /var/lib/nginx $JAIL/var/lib/nginx そして必要なライブラリをコピーします。ldd を使ってライブラリを確認して適当な場所にコピーして下さい。ハードリンクよりはコピーが推奨されます。攻撃者が書き込み権限を得たときに本当のシステムファイルが破壊されたり改変される可能性があるためです。 {{hc|$ ldd /usr/bin/nginx|<nowiki> linux-vdso.so.1 (0x00007fffc41fe000) libpthread.so.0 => /usr/lib/libpthread.so.0 (0x00007f57ec3e8000) libcrypt.so.1 => /usr/lib/libcrypt.so.1 (0x00007f57ec1b1000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f57ebead000) libm.so.6 => /usr/lib/libm.so.6 (0x00007f57ebbaf000) libpcre.so.1 => /usr/lib/libpcre.so.1 (0x00007f57eb94c000) libssl.so.1.0.0 => /usr/lib/libssl.so.1.0.0 (0x00007f57eb6e0000) libcrypto.so.1.0.0 => /usr/lib/libcrypto.so.1.0.0 (0x00007f57eb2d6000) libdl.so.2 => /usr/lib/libdl.so.2 (0x00007f57eb0d2000) libz.so.1 => /usr/lib/libz.so.1 (0x00007f57eaebc000) libGeoIP.so.1 => /usr/lib/libGeoIP.so.1 (0x00007f57eac8d000) libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x00007f57eaa77000) libc.so.6 => /usr/lib/libc.so.6 (0x00007f57ea6ca000) /lib64/ld-linux-x86-64.so.2 (0x00007f57ec604000)</nowiki>}} # cp /lib64/ld-linux-x86-64.so.2 $JAIL/lib {{ic|/usr/lib}} の中にあるファイルについては次のワンライナーが使えます: {{bc|<nowiki># cp $(ldd /usr/bin/nginx | grep /usr/lib | sed -sre 's/(.+)(\/usr\/lib\/\S+).+/\2/g') $JAIL/usr/lib</nowiki>}} {{Note|{{ic|linux-vdso.so}} をコピーしないでください – 実際のライブラリではなく {{ic|/usr/lib}} には存在しません。64ビット環境の場合 {{ic|ld-linux-x86-64.so}} も {{ic|/lib64}} にあるように表示されます。}} 必要なライブラリとシステムファイル以外のファイルをコピーします。 {{bc|# cp /usr/lib/libnss_* $JAIL/usr/lib # cp -rfvL /etc/{services,localtime,nsswitch.conf,nscd.conf,protocols,hosts,ld.so.cache,ld.so.conf,resolv.conf,host.conf,nginx} $JAIL/etc}} chroot のために制限を付けたユーザー・グループファイルを作成します。これにより chroot にアクセスするのに必要なシステムユーザー・グループが攻撃者に漏洩しなくなります。 {{hc|$JAIL/etc/group| http:x:33: nobody:x:99: }} {{hc|$JAIL/etc/passwd| http:x:33:33:http:/:/bin/false nobody:x:99:99:nobody:/:/bin/false }} {{hc|$JAIL/etc/shadow| http:x:14871:::::: nobody:x:14871:::::: }} {{hc|$JAIL/etc/gshadow| http::: nobody::: }} # touch $JAIL/etc/shells # touch $JAIL/run/nginx.pid 最後にパーミッションをできるだけ制限的に設定してください。できるかぎり所有者を root にして書き込み不可にします。 # chown -R root:root $JAIL/ # chown -R http:http $JAIL/www # chown -R http:http $JAIL/etc/nginx # chown -R http:http $JAIL/var/{log,lib}/nginx # chown http:http $JAIL/run/nginx.pid # find $JAIL/ -gid 0 -uid 0 -type d -print | xargs sudo chmod -rw # find $JAIL/ -gid 0 -uid 0 -type d -print | xargs sudo chmod +x # find $JAIL/etc -gid 0 -uid 0 -type f -print | xargs sudo chmod -x # find $JAIL/usr/bin -type f -print | xargs sudo chmod ug+rx # find $JAIL/ -group http -user http -print | xargs sudo chmod o-rwx # chmod +rw $JAIL/tmp # chmod +rw $JAIL/run サーバーがポート 80 (あるいは 0-1024 のどれかのポート) で待機する場合、chroot した実行ファイルに root 権限がなくてもポートを使えるように権限を与えてください: # setcap 'cap_net_bind_service=+ep' $JAIL/usr/bin/nginx === nginx.service を変更して chroot を起動 === {{ic|nginx.service}} ユニットファイルを編集する前に、ユニットファイルを {{ic|/etc/systemd/system/}} にコピーして {{ic|/usr/lib/systemd/system/}} のファイルよりも優先されるようにすると良いでしょう。nginx をアップグレードしたときにカスタムした ''.service'' ファイルが変更されなくなります。 # cp /usr/lib/systemd/system/nginx.service /etc/systemd/system/nginx.service chroot で nginx を起動するために systemd ユニットを変更して、pid ファイルを chroot に保存します。 {{Note|I'm not sure if the pid file needs to be stored in the chroot jail.}} {{hc|/etc/systemd/system/nginx.service|<nowiki> [Unit] Description=A high performance web server and a reverse proxy server After=syslog.target network.target [Service] Type=forking PIDFile=/srv/http/run/nginx.pid ExecStartPre=/usr/bin/chroot --userspec=http:http /srv/http /usr/bin/nginx -t -q -g 'pid /run/nginx.pid; daemon on; master_process on;' ExecStart=/usr/bin/chroot --userspec=http:http /srv/http /usr/bin/nginx -g 'pid /run/nginx.pid; daemon on; master_process on;' ExecReload=/usr/bin/chroot --userspec=http:http /srv/http /usr/bin/nginx -g 'pid /run/nginx.pid; daemon on; master_process on;' -s reload ExecStop=/usr/bin/chroot --userspec=http:http /srv/http /usr/bin/nginx -g 'pid /run/nginx.pid;' -s quit [Install] WantedBy=multi-user.target</nowiki>}} {{Note|Upgrading nginx with pacman will not upgrade the chrooted nginx installation. You have to take care of the updates manually by repeating some of the steps above. Do not forget to also update the libraries it links against.}} chroot されていない nginx 環境は取り除いてもかまいません: # pacman -Rsc nginx chroot されていない nginx 環境を削除しない場合、実行中の nginx プロセスが chroot されているプロセスかどうか確認したくなるときがあるかもしれません。{{ic|/proc/''PID''/root}} シンボリックリンクを確認することでチェックできます。 # ps -C nginx | awk '{print $1}' | sed 1d | while read -r PID; do ls -l /proc/$PID/root; done == ヒントとテクニック == === systemd を使用したユーザーサービスの実行 === 権限のないユーザーが完全に制御して構成できるサーバーインスタンスを実行したい場合は、{{AUR|nginx-user-service}} の使用を検討してください。 === [[systemd]] を使って非特権で動作させる === {{ic|nginx.service}} の[[ドロップインファイル]]を使用して、{{ic|[Service]}} の下の {{ic|User}} と任意で {{ic|Group}} を設定します。 {{hc|/etc/systemd/system/nginx.service.d/user.conf|2= [Service] User=''user'' Group=''group'' }} 権限昇格に対してサービスを防御することができます: {{hc|/etc/systemd/system/nginx.service.d/user.conf|2= [Service] ... NoNewPrivileges=yes }} {{Tip|1=制限オプションについて詳しくは [http://www.freedesktop.org/software/systemd/man/systemd.exec.html#User= systemd.exec(5)] を見てください。}} それから {{ic|''user''}} が必要なファイルやポートにアクセスできるようにしてください。以下の項目に従って、nginx を[[起動]]します。 {{Tip|[[#FastCGI|FastCGI サーバー]] でも同じ設定が望ましい場合があります。}} ==== ポート ==== Linux はデフォルトでは {{ic|root}} 以外が 1024 以下のポートを使うことができないようになっています。1024 よりも上のポートは使うことができます: {{hc|/etc/nginx/nginx.conf| server { listen 8080; } }} {{Tip|1=nginx にポート 80 あるいは 443 からアクセスできるようにしたい場合、[[ファイアウォール]]を設定して 80 あるいは 443 から nginx が listen しているポートに転送してください。}} </dd> <dd> また、nginx プロセスに CAP_NET_BIND_SERVICE ケイパビリティを付与することで 1024 以下のポートにバインドできるようになります: {{hc|/etc/systemd/system/nginx.service.d/user.conf|2= [Service] ... CapabilityBoundingSet= CapabilityBoundingSet=CAP_NET_BIND_SERVICE AmbientCapabilities= AmbientCapabilities=CAP_NET_BIND_SERVICE }} </dd> ==== PID ファイル ==== {{Pkg|nginx}} はデフォルトでは {{ic|/run/nginx.pid}} を使います。''user'' が書き込み可能なディレクトリを作成して PID ファイルをそこに配置します。[[systemd#一時ファイル|systemd-tmpfiles]] を使用する例: {{hc|/etc/tmpfiles.d/nginx.conf|2= d /run/nginx 0775 root ''group'' - - }} 設定を実行: # systemd-tmpfiles --create 元の {{ic|nginx.service}} に合わせて PID の値を[[編集]]: {{hc|/etc/systemd/system/nginx.service.d/user.conf|2= [Service] ... PIDFile=/run/nginx/nginx.pid ExecStart= ExecStart=/usr/bin/nginx -g 'pid /run/nginx/nginx.pid; error_log stderr;' ExecReload= ExecReload=/usr/bin/nginx -s reload -g 'pid /run/nginx/nginx.pid;' }} </dd> ==== {{ic|/var/lib/nginx/*}} ==== {{ic|/var/lib/nginx}} の一部のディレクトリは {{ic|root}} として nginx でブートストラップする必要があります。サーバー全体を起動する必要はありません。nginx は[[#設定の確認|設定テスト]]でブートストラップを実行します。一回実行すればそれで十分です。 </dd> ====ログファイル & ディレクトリのパーミッション==== 設定テストの実行時に {{ic|root}} によって所有される壊れたログが作成されます。{{ic|/var/log/nginx}} のログを削除して新しく起動してください。 nginx サービスのユーザーから {{ic|/var/log/nginx}} に書き込む権限が必要です。[[ファイルのパーミッションと属性#パーミッションを変更|パーミッションを変更]]するかディレクトリの所有者を変更してください。 === systemd の別のスクリプト === 純粋な systemd では、chroot + systemd の利点を得ることができます。[http://0pointer.de/blog/projects/changing-roots.html] セット [https://wiki.nginx.org/CoreModule#user ユーザーグループ] と pid に基づいて次のようにします。 {{hc|/etc/nginx/nginx.conf|2= user http; pid /run/nginx.pid; }} ファイルの絶対パスは {{ic|/srv/http/etc/nginx/nginx.conf}} です。 {{hc|/etc/systemd/system/nginx.service|2= [Unit] Description=nginx (Chroot) After=syslog.target network.target [Service] Type=forking PIDFile=/srv/http/run/nginx.pid RootDirectory=/srv/http ExecStartPre=/usr/bin/nginx -t -c /etc/nginx/nginx.conf ExecStart=/usr/bin/nginx -c /etc/nginx/nginx.conf ExecReload=/usr/bin/nginx -c /etc/nginx/nginx.conf -s reload ExecStop=/usr/bin/nginx -c /etc/nginx/nginx.conf -s stop [Install] WantedBy=multi-user.target }} デフォルトの場所を設定する必要はありません。nginx はデフォルトでロードされます。{{ic| -c /etc/nginx/nginx.conf}} ですが、これは良い考えです。 あるいは、パラメータ {{ic|RootDirectoryStartOnly}} を {{ic|yes}} に設定して chroot として '''only''' {{ic|ExecStart}} を実行することもできます。({{man|5|systemd.service}} を参照) またはマウントポイントが有効になる前、または systemd パス ({{man|5|systemd.path}} を参照) が利用可能になる前に起動します。 {{hc|/etc/systemd/system/nginx.path|2= [Unit] Description=nginx (Chroot) path [Path] PathExists=/srv/http/site/Public_html [Install] WantedBy=default.target }} 作成された {{ic|nginx.path}} を [[有効化]] し、{{ic|1=WantedBy=default.target}} を {{ic|1=WantedBy=nginx.path}} に変更します|/etc/systemd/system/nginx.service}} ユニットファイル内の {{ic|PIDFile}} により、systemd がプロセスを監視できるようになります (絶対パスが必要です) 望ましくない場合は、デフォルトのワンショットタイプに変更し、ユニットファイルから参照を削除できます。 === Nginx Beautifier === {{AUR|nginxbeautifier}} は nginx の設定ファイルを整形することができるコマンドラインツールです。 === より良いヘッダー管理 === Nginx のヘッダー管理システムはあまり直感的とは言えません。ヘッダーは特定のコンテキストでしか定義できず、他のヘッダーは無視されます。[https://github.com/openresty/headers-more-nginx-module#more_set_headers headers-more-nginx] モジュールをインストールすることでこの挙動を変更できます。 {{Pkg|nginx-mod-headers-more}} パッケージを[[インストール]]してください。モジュールは {{ic|/usr/lib/nginx/modules}} ディレクトリにインストールされます。 モジュールをロードするには以下をメインの nginx の設定ファイルに追加してください: {{hc|/etc/nginx/nginx.conf|2= load_module "/usr/lib/nginx/modules/ngx_http_headers_more_filter_module.so"; ... }} === 基本認証 === 基本認証ではパスワードファイルの作成が必要です。パスワードファイルは、{{Pkg|apache}} パッケージで提供される {{ic|htpasswd}} プログラムを使用するか、{{ic|nginx-passwd}} を提供する {{AUR|nginx_passwd}} を使用して管理できます。詳細は、次のサイトで確認できます。 [https://github.com/gene-git/nginx_passwd github ソース] == トラブルシューティング == === 設定の確認 === {{hc|# nginx -t| nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful }} === Error: The page you are looking for is temporarily unavailable. Please try again later. (502 Bad Gateway) === This is because the FastCGI server has not been started, or the socket used has wrong permissions. Try [https://stackoverflow.com/questions/4252368/nginx-502-bad-gateway/16497957#16497957 out this answer] to fix the 502 error. In Arch Linux, the configuration file mentioned in above link is {{ic|/etc/php/php-fpm.conf}}. === Error: No input file specified === 1. Verify that variable {{ic|open_basedir}} in {{ic|/etc/php/php.ini}} contains the correct path specified as {{ic|root}} argument in {{ic|nginx.conf}} (usually {{ic|/usr/share/nginx/}}). When using [https://php-fpm.org/ PHP-FPM] as FastCGI server for PHP, you may add {{ic|<nowiki>fastcgi_param PHP_ADMIN_VALUE "open_basedir=$document_root/:/tmp/:/proc/"</nowiki>;}} in the {{ic|location}} block which aims for processing php file in {{ic|nginx.conf}}. 2. Another occasion is that, wrong {{ic|root}} argument in the {{ic|location ~ \.php$}} section in {{ic|nginx.conf}}. Make sure the {{ic|root}} points to the same directory as it in {{ic|location /}} in the same server. Or you may just set root as global, do not define it in any location section. 3. Check permissions: e.g. {{ic|http}} for user/group, {{ic|755}} for directories and {{ic|644}} for files. Remember the entire path to the {{ic|html}} directory should have the correct permissions. See [[ファイルのパーミッションと属性#まとめて chmod]] to bulk modify a directory tree. 4. おそらくスクリプトのフルパスを含んだ SCRIPT_FILENAME がありません。 nginx の設定 (fastcgi_param SCRIPT_FILENAME) が完全でも、このエラーは php が requestd スクリプトをロードできないことを意味しています。これは単純にパーミッションの問題であることが普通で、root で php-cgi を実行するか # spawn-fcgi -a 127.0.0.1 -p 9000 -f /usr/bin/php-cgi php-cgi を起動するグループとユーザーを作成する必要があります。例えば: # groupadd www # useradd -g www www # chmod +w /srv/www/nginx/html # chown -R www:www /srv/www/nginx/html # spawn-fcgi -a 127.0.0.1 -p 9000 -u www -g www -f /usr/bin/php-cgi 5. If you are running php-fpm with chrooted nginx ensure {{ic|chroot}} is set correctly within {{ic|/etc/php-fpm/php-fpm.d/www.conf}} (or {{ic|/etc/php-fpm/php-fpm.conf}} if working on older version) === Warning: Could not build optimal types_hash === When starting the {{ic|nginx.service}}, the process might log the message: [warn] 18872#18872: could not build optimal types_hash, you should increase either types_hash_max_size: 1024 or types_hash_bucket_size: 64; ignoring types_hash_bucket_size To fix this warning, increase the values for these keys inside the {{ic|http}} block [https://nginx.org/en/docs/http/ngx_http_core_module.html#types_hash_max_size] [https://nginx.org/en/docs/http/server_names.html]: {{hc|/etc/nginx/nginx.conf| http { types_hash_max_size 4096; server_names_hash_bucket_size 128; ... } }} === Cannot assign requested address === {{ic|nginx.service}} [[ユニットステータス]]からの完全なエラーは次のとおりです。 [emerg] 460#460: bind() to A.B.C.D:443 failed (99: Cannot assign requested address) nginx ユニット ファイルが systemd を使用して {{ic|network.target}} の後に実行するように設定されている場合でも、nginx は、構成されているがどのインターフェイスにもまだ追加されていないアドレスでリッスンしようとする場合があります。 nginx の [[開始]]を手動で実行して、これが当てはまることを確認します (これにより、IP アドレスが適切に設定されていることが示されます)。任意のアドレスをリッスンするように nginx を設定すると、この問題が解決します。ユースケースで特定のアドレスをリッスンする必要がある場合、考えられる解決策の 1 つは、systemd を再構成することです。 設定されたすべてのネットワークデバイスが起動し、IP アドレスが割り当てられた後に nginx を起動するには、{{ic|nginx.service}} 内の {{ic|1=After=}} に {{ic|network-online.target}} を追加し、{{ic|systemd-networkd-wait-online.service}} を[[起動/有効化]]にします。 == 参照 == * [[WebDAV#nginx|WebDAV with nginx]] * [https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ nginx configuration pitfalls] * [https://calomel.org/nginx.html Very good in-depth 2014 look at nginx security and Reverse Proxying] * [https://www.tecmint.com/install-nginx-php-mysql-with-mariadb-engine-and-phpmyadmin-in-arch-linux/ Installing LEMP (nginx, PHP, MySQL with MariaDB engine and PhpMyAdmin) in Arch Linux] * [[Let’s Encrypt|Using SSL certificates generated with Let's Encrypt]]
このページで使用されているテンプレート:
テンプレート:AUR
(
ソースを閲覧
)
テンプレート:Bc
(
ソースを閲覧
)
テンプレート:Hc
(
ソースを閲覧
)
テンプレート:Ic
(
ソースを閲覧
)
テンプレート:Lowercase title
(
ソースを閲覧
)
テンプレート:Man
(
ソースを閲覧
)
テンプレート:Note
(
ソースを閲覧
)
テンプレート:Pkg
(
ソースを閲覧
)
テンプレート:Tip
(
ソースを閲覧
)
テンプレート:Warning
(
ソースを閲覧
)
Nginx
に戻る。
検索
検索
Nginxのソースを表示
話題を追加