Apache

DebianのApacheについて

 

mod_rewriteのインストール

 

1)# a2enmod rewrite  コマンドの実行

2).htaccessファイルの設定を有効にするために、 /etc/apache2/site-avaiable/default で使用するディレクトリで AlloOverride All  に設定します。

その後Apache2に再起動 /etc/init.d/apache2 restart

 

仮想サイトの追加

 

環境 Debian GNU/Linux 4.0 以降

1) /etc/apache2/sites-avaiable にdefaultファイルを参考にして、追加するサイトの設定ファイルを作成します。

2) シンボリックリンク作成の代わりにDebianのApacheコマンドで追加作成、削除します。以下のコマンドは、 /etc/apache2/sites-enabled で実行します。

新規作成 "a2ensite サイト名"  削除の場合 "a2dissite サイト名"

3) Apacheの再読込  # /etc/init.d/apache2 reload

 

  • Apacheのデフォルトドメインを停止する(仮想ドメインを使う場合)

他の仮想ホストに干渉する可能性があるため、デフォルトの仮想ホストを無効にします。

sudo a2dissite 000-default.conf

 

Apacheモジュールの追加

 

新規作成  "a2enmod サイト名"   サイト削除  "a2dismod サイト名"

mod_pagespeedを追加する場合:

Googleのmod_pagespeedサイトから最新版をダウンロード

dpkg -i mod-pagespeedモジュールファイル

もしくは

apt-get -f install mod-pagespeedモジュールファイル

確認で、/etc/apache2/mods-available と mods-enabled で pagespeed.conf pagespeed.load が設定されているか確認、もしくは e2enmod mod_pagespeed を実行して既にインストール済になっているか確認します。

その後、apache2を再起動

 

Apacheのログ

標準ログは、/var/log/apache2   に保存されます。 access.log   error.log という名前になります。 リアルタイムで動作を調べるときには、 tail -f access.log -n 100  などでモニターでき、便利です。

 

.htaccessを使わない設定方法

.htaccess のファイル名を変更します。
/etc/apache2 にある apache2.conf で AccessFileName .htaccess という行を
コメントに設定する(読み込まないようにする)
/etc/apache2 にある httpd.conf  に .htaccess の内容をコピーする。この
設定ファイルで、RewriteRuleなどを設定する。 なを、/etc/apache2/sites- avaiable/
以下の仮想ドメイン用の設定ファイルには、RewriteEngine ON を設定して下さい。

 

エラーが起きた場合

Apache2を起動時に、 using 127.0.0.1 for ServerName などのエラーメッセージが表示される場合は、/etc/apache2/apache2.conf の最後の行に、 ServerName hoge.hogedomain.com:80  を記入し、Apache2を再起動してエラーメッセージが表示されるか確認します。

DebianのOSを更新した際に、Apacheのアップデイトなど、関連ファイルが更新され、古い設定ファイルなどが残っている場合があります。 その場合は、以下のようなエラーメッセージが表示されることがあります。

apache2: Syntax error on line 140 of /etc/apache2/apache2.conf: Syntax error on line 1 of /etc/apache2/mods-enabled/php5.load: Cannot load /usr/lib/apache2/modules/libphp5.so into server: /usr/lib/apache2/modules/libphp5.so: cannot open shared object file: No such file or directory Action 'configtest' faile

このようなエラーの場合は、apacheの設定ファイルなどをバックアップし、その後、ディレクトリなども削除する apt-get --purge remove apache2 を実行します。

 

 

ディレクトリやファイルなどのインデックスを非表示にたい

Apache2の場合、 /etc/apache2/sites-available/default ファイルを修正し、apache2を再起動します。

修正箇所は、Options Indexes FollowSymLinks MultiViews の行で Indexes  を削除します。

 

SSLの設定

サーバー内で証明書も発行する場合

参考にしたサイト: https://symfoware.blog.fc2.com/blog-entry-1120.html

環境 Debian 8,9

 

OpenSSLのインストールと設定

# apt-get install openssl

# cd /etc/ssl/certs/
# openssl genrsa -des3 -out server.key 1024

任意のパスフレーズを入力

Apacheの起動のたびに、パスフレーズの入力を求められので、削除します。

# openssl rsa -in server.key -out server.key

これで秘密鍵の準備は出来ました。今度はサーバー証明書を作成します。証明書要求の作成を行います。

# openssl req -new -days 3650 -key server.key -out server.csr

......  Common Name (e.g. server FQDN or YOUR name) []:192.168.1.3 <-www.example.comまたはIPアドレス

...... A challenge password []:(空白)
...... An optional company name []:(空白)

証明書を発行してもらうための要求ファイルができたので、証明書を発行

# openssl x509 -in server.csr -out server.crt -req -signkey server.key -days 3650

これでもう、server.csrは不要です。パーミッションを変更します。

# chmod 400 server.*

server.keyが秘密鍵。server.crtがサーバー証明書。

 

Apache2へSSLの設定

SSLモジュールの有効化

# a2enmod ssl

/etc/apache2/sites-available/default-ssl.conf を編集して、ServerNameと作成した秘密鍵、公開鍵のパスを指定。

# vi /etc/apache2/sites-available/default-ssl.conf

<IfModule mod_ssl.c>
<VirtualHost _default_:443>
        ServerAdmin webmaster@localhost
        ServerName 192.168.1.3:443 <-サーバー名もしくはIPアドレス

.......

# SSLCertificateFile directive is needed.
        SSLCertificateFile    /etc/ssl/certs/server.crt
        SSLCertificateKeyFile /etc/ssl/certs/server.key

SSLサイトの有効化

# a2ensite default-ssl

Apache2再起動  # /etc/init.d/apache2 restart

 

パスワードを自動読み込みに設定する場合

/etc/ssl/private/ディレクトリに、例えばmy_passphrase.shファイルを作成します。

 #!/bin/sh
 echo "設定したパスワード"

管理者のみ実行権限付きパーミッションに変更

 chmod 500 /etc/ssl/private/my_passphrase.sh

/etc/apache2/mods-available/ssl.confの修正

 SSLPassPhraseDialog exec:/etc/ssl/private/my_passphrase.sh

Apache2再起動

参考にしたページ:

https://def-4.com/ssl-passphrase/

 

常時SSL化の設定

HTTPからHTTPSへのリダイレクト

参考にしたサイト: https://www.tecmint.com/redirect-http-to-https-on-apache/

https://www.yokoweb.net/2017/03/23/ubuntu-wordpress-ssl-coressl/

.htaccessファイルを使う場合

Mod Rewirte の実行 $ sudo a2enmod rewrite

使用するドメインルートディレクトリに.htaccess ファイルの作成し以下の設定を記載

RewriteEngine On 
RewriteCond %{HTTPS}  !=on 
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

もしくは

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

Apache2の再起動

 

仮想ドメインでSSLを運用

参考にしたサイト: 

http://www.techspacekh.com/installing-and-configuring-apache-web-server-...

https://letsencrypt.jp/usage/#ExecClientSoftware

https://www.tecmint.com/install-free-lets-encrypt-ssl-certificate-for-ap...

https://qiita.com/ninneko/items/87a76f0f1dc6d82500fb

https://linux-svr.com/tips/Web%E3%82%B5%E3%83%BC%E3%83%90/12.php

 

  • Debian 8 jessie の場合

opensslで既にSSL(インストールされているサーバーで認証サーバーも兼用する)環境が設定ずみとして、

apacheのバーチャルホストの設定で

/etc/apache2/sites-available/www.XXXcom.conf のファイルを編集します。

VirtualHost *:443 以下を追加

 <VirtualHost *:80>
     ServerName www.XXX.com
     DocumentRoot /var/www/html/xxx
     ServerAlias XXX.com
     CustomLog /var/log/apache2/xxx-80-access_log common
     ErrorLog /var/log/apache2/xxx-80-error_log

 <Directory "/var/www/html/xxx">
                        Options FollowSymLinks
                        AllowOverride All

                        Require all granted

                </Directory>

 </VirtualHost> 

 <VirtualHost *:443>

     ServerName www.XXX.com
     ServerAdmin xxx@xxx.com
     DocumentRoot /var/www/html/xxx
     ServerAlias xxx.com
     CustomLog /var/log/apache2/xxx-443-access_log common
     ErrorLog /var/log/apache2/xxx-443-error_log

 <Directory "/var/www/html/xxx">
                        Options FollowSymLinks
                        AllowOverride All

                        Require all granted

                </Directory>

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/server.crt
    SSLCertificateKeyFile /etc/ssl/certs/server.key

</VirtualHost>

この状態だと、http と https の両方が稼働する状態なので、常時、httpsへ切り替わるように設定します。

httpからhttpsへリダイレクトする方法として、以下のようにhttpのタグにリライトを設定します。

<VirtualHost *:80>

 <Directory ...>

 ................................

 </Directory>

   RewriteEngine on
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule ^/(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

</VirtualHost>

 

  • Let's encryptで認証する場合(Debian 8 jessieの場合)

新しい設定ファイル /etc/apt/sources.list.d/backport.list を用意して,以下の内容を記述します。

 deb http://ftp.debian.org/debian jessie-backports main

次に、Debianの更新 sudo apt update

jessie-backports から python-certbot-apacheをインストール

 apt install python-certbot-apache -t jessie-backports

これで、certbotコマンドが実行できるようになります。

認証ファイルの作成 (www.xxxx.co.jpxxxx.co.jpの2つのパターンに対応する)

 sudo certbot certonly --webroot -w /var/www/html/xxxx -d www.xxxx.co.jp -d xxxx.co.jp

できた、cert.pem  chain.pem  fullchain.pem  privkey.pem をApacheのファイルで設定します。

/etc/apache2/sites-available/www.xxxx.co.jp.conf のファイルに以下の項目を追加

    SSLEngine on

    SSLCertificateFile /etc/letsencrypt/live/www.xxxx.co.jp/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/www.xxxx.co.jp/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/www.xxxx.co.jp/chain.pem

 

最後に、自動更新の設定

 sudo certbot renew

動作の確認は sudo systemctl |grep certbot

 

 

  • Let's encryptで認証する場合(Debian 9 stretchの場合)

参考にしたサイト:http://www.kmiura.net/archives/8801264.html

certbotのインストールとバージョンの確認

sudo apt-get update 
sudo apt-get install -y certbot
sudo certbot --version
certbot 0.10.2

以下のコマンドを実行して、SSL認証ファイルを生成

certbot certonly --webroot -w /var/www/html -d www.XXXX.com -d XXXX.com

連絡先メールアドレスを設定、ライセンスの確認をすれば、SSL認証ファイルができます。

 

  • Let's encryptで認証する場合(Debian 10 Busterの場合)

Apacheの場合は https://certbot.eff.org/lets-encrypt/debianbuster-apache.html

インストール: sudo apt-get install certbot python-certbot-apache

証明書の発行: sudo certbot --apache -d www.gennai3.co.jp -d gennai3.co.jp

自動更新の設定: sudo certbot renew --dry-run

以下にインストールされます

/etc/crontab/

/etc/cron.*/*

systemctl list-timers

 

  • Let's encryptで wwwあり-> wwwなし で認証する場合(Debianの場合)

SSLなしのドメインの設定 一般的なApacheでの設定 www.xxx.jp.conf

######################################################################
# URL: http://www.xxx.jp/
######################################################################
<VirtualHost *:80>
    ServerName www.xxx.jp
    DocumentRoot /var/www/html/0000
    ServerAlias xxx.jp
    CustomLog /var/log/apache2/0000/xxx-80-access_log common
    ErrorLog /var/log/apache2/0000/xxx-80-error_log

<Directory "/var/www/html/0000">
                        Options FollowSymLinks MultiViews
                        AllowOverride All
                        Require all granted
                </Directory>
</VirtualHost>

このサイトがSSLなしで見れることを確認してから、sudo cetbot --apache コマンドを実行する

その際に、 www.xxx.jp  と xxx.jp のどちらをSSL対応にするか確認があるので、xxx.jp を選択します。

 www.xxx.jp.confファイルに以下の内容が追加されます。

RewriteEngine on
RewriteCond %{SERVER_NAME} =xxx.jp [OR]
RewriteCond %{SERVER_NAME} =www.xxx.jp
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

さらに、SSL対応のファイルが追加されます。www.xxx.jp-le-ssl.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName www.xxx.jp
    DocumentRoot /var/www/html/0000
    ServerAlias xxx.jp
    CustomLog /var/log/apache2/0000/xxx-80-access_log common
    ErrorLog /var/log/apache2/0000/xxx-80-error_log

<Directory "/var/www/html/0000">
                        Options FollowSymLinks MultiViews
                        AllowOverride All
                        Require all granted
                </Directory>

SSLCertificateFile /etc/letsencrypt/live/xxx.jp/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/xxx.jp/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

 

 

  • CertbotコマンドでApacheのLet's encrypt認証書を取得する場合(Debian 11 bullseyeの場合)

$ sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com

--apache: Use the Apache plugin.
--agree-tos: Agree to terms of service.
--redirect: Force HTTPS by 301 redirect.
--hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
--staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.

 

  • PostfixのTLSで使用するLet's encryptで認証書だけを取得する場合(Debian 11 bullseyeの場合)

$ sudo certbot certonly -a apache --agree-tos --no-eff-email --staple-ocsp --email 名前@gmail.com -d mail.ドメイン名.biz
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Account registered.
Requesting a certificate for mail.ドメイン名.biz
Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/mail.ドメイン名.biz/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/mail.ドメイン名.biz/privkey.pem

certonly: TLS 証明書を取得しますが、Web サーバーにはインストールしません。
-a nginx: 認証に Apache プラグインを使用する
--agree-tos: 利用規約に同意します。
--no-eff-email: EFF財団からのメールを受け取りません。
--staple-ocsp: OCSP ステープルを有効にします。有効な OCSP 応答は、TLS 接続中にサーバーが提供する証明書にステープルされます。
--email: 重要な通知とアカウントの復旧に使用するメール アドレスを入力します。
-d: ドメイン、つまりメール サーバーのホスト名。

 

  • Apacheのデフォルトドメインを停止する(仮想ドメインを使う場合)

他の仮想ホストに干渉する可能性があるため、デフォルトの仮想ホストを無効にします。

sudo a2dissite 000-default.conf

 

  • Certbotの証明書再発行を自動化

crontabに毎日certbot renew を実行し、postfixとdovecot を再起動、Apacheの場合

sudo crontab -e
@daily certbot renew --quiet && systemctl reload postfix dovecot apache2

 

  • Certbotの証明書を削除

登録されている証明書の確認

sudo certbot certificates

証明書の削除

sudo certbot delete --cert-name 登録ドメイン名

 

Basic認証の設定

オープンソースCMS Drupalの運用環境で、Basic認証を設定する場合

apache2のhtpasswdを追加インストール

 # aptitude -y install apache2-utils

認証ユーザー名とパスワードを設定します。パスワードファイル(.htpasswd)は/etc/apache2に保存する場合

 # htpasswd -c /etc/apache2/.htpasswd ユーザー名

Drupalのdrupal_rootディレクトリにある、.htaccessファイルのトップ行に以下の内容を追記します。

AuthUserFile /etc/apache2/.htpasswd
AuthName "Input ID and Password."
AuthType Basic
Require valid-user
<Files ~ "^.(htpasswd|htaccess)$">
        Require all denied
</Files>

Apache2を再起動。

 

リバースプロキシーの設定

出典: https://docs.graylog.org/docs/web-interface#configuring-webif-nginx

HTTPの場合

<VirtualHost *:80>
    ServerName xxx.example.org
    ProxyRequests Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location />
        RequestHeader set X-xxx-Server-URL "http://xxx.example.org/"
        ProxyPass http://127.0.0.1:9000/
        ProxyPassReverse http://127.0.0.1:9000/
    </Location>

</VirtualHost>

HTTPSの場合

<VirtualHost *:443>
    ServerName xxx.example.org
    ProxyRequests Off
    SSLEngine on
    # <- your SSL Settings here!

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location />
        RequestHeader set X-xxx-Server-URL "https://xxx.example.org/"
        ProxyPass http://127.0.0.1:9000/
        ProxyPassReverse http://127.0.0.1:9000/
    </Location>

</VirtualHost>

 

 

タグ: