얕고넓은지식/linux

ubuntu 20.04 웹서버 한방에 따라하기 2 가상호스트 설정

쪽마 2022. 2. 5. 02:16
반응형

모든 설정은

개인서버기준이므로..

sudo passwd root

위 명령어로  루트로 로그인하도록한다

패스워드 설정해주면된다

앞으로

sudo  슈퍼유저두~ 는 빼도록한다

 

root@linux:/# mkdir -pv /var/www/html/virtualhost

root@linux:/# chmod 775 -R /var/www/html/virtualhost

root@linux:/# vi /var/www/html/virtualhost/index.php

아래 내용을 넣어주고 저장하자

<html>
  <body>
    <p>virtual host </p>
  </body>
</html>

 

root@linux:/# vi /etc/apache2/sites-available/virtualhost.conf

<VirtualHost *:80>
    # ServerAdmin webmaster@virtualhost.net
    ServerName www.virtualhost.net
    ServerAlias virtualhost.net
    DocumentRoot /var/www/html/virtualhost.net
    DirectoryIndex index.html
    ErrorLog $/virtualhost.net_error.log
    CustomLog $/virtualhost.net_access.log combined
</VirtualHost>

<Directory /var/www/html/virtualhost.net>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

root@linux:/# a2ensite virtualhost.conf

root@linux:/# apache2ctl configtest

위와같은 오류가뜬다

 

root@linux:/#  grep ServerName /etc/apache2/apache2.conf

ServerName이 지정되지 않았다.

root@linux:/# echo "ServerName localhost" >> /etc/apache2/apache2.conf

root@linux:/# grep ServerName /etc/apache2/apache2.conf

root@linux:/# systemctl reload apache2

root@linux:/# vi /etc/hosts

127.0.0.1 localhost
127.0.1.1 anonymous-desktop
127.0.2.1   virtualhost.net

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

127.0.2.1   virtualhost.net 를 추가해준다

 

OpenSSL 패키지 설치해주자

root@linux:/# apt install openssl

root@linux:/# openssl version

root@linux:/# mkdir -pv /etc/ssl/ssc

root@linux:/# cd /etc/ssl/ssc

root@linux:/etc/ssl/ssc# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout virtualhost.net.key -out virtualhost.net.key.crt

 

req
req 명령은 주로 PKCS #10 형식으로 인증서 요청을 만들고 처리합니다. 예를 들어 루트 CA로 사용할 자체 서명된 인증서를 추가로 만들 수 있음

-x509
x.509는 암호학에서 공개키 인증서와 인증 알고리즘의 표준 가운데 공개키 기반(PKI)의 ITU-T 표준

OpenSSL에서 이 옵션을 사용한다는 것은 인증서 요청(CSR) 대신 자체 서명된 인증서를 출력합니다. 일반적으로 테스트 인증서 또는 자체 서명된 루트 CA를 생성하는 데 사용

-nodes
개인키를 생성 시 암호화하지 않음

-days 365
해당 인증서의 유효 기간을 설정합니다. 이 옵션을 지정하지 않으면 기본값으로 30일이 지정

-newkey rsa:2048
새 인증서 요청과 새 개인키를 생성합니다. 뒤이어 오는 인수는 쌍점(:)으로 구별되어 전자는 암호 알고리즘이고, 후자는 비트수

즉, rsa:2048는 RSA 알고리즘으로 2048비트 수의 RSA 키를 생성

-keyout virtualhost.net.key
새로 생성된 개인키를 사용할 파일을 지정합니다.

-out virtualhost.net.key.crt
기본적으로 기록할 출력 파일 이름 또는 표준 출력을 지정.

 

생성되었는지 확인

root@linux:/etc/ssl/ssc# ls -l

확장자가 key인 파일은 SSLCertificateKeyFile

확장자가 crt인 파일은 SSLCertificateFile과 SSLCertificateChainFile

 

 

인증서 디렉터리와 파일 소유권 및 권한 조정을 통한 보안 설정

root@linux:/# chown -R root:root /etc/ssl/ssc

root@linux:/# chmod 600 /etc/ssl/ssc/*.*

root@linux:/# chmod 700 /etc/ssl/ssc

 

 

방화벽 설정

 

방화벽 활성화

root@linux:/# ufw enable

방화벽확인

root@linux:/# ufw status

방화벽확인방법 포트번호화 프로톸로도 확인가능

root@linux:/# ufw status verbose

 

root@linux:/# ufw allow "Apache Full"

root@linux:/# ufw status

root@linux:/# ufw allow 1980

root@linux:/# ufw allow ssh

 

Apache2 서버 설정

root@linux:/# a2enmod ssl

a2enmod
a2enmod는 인수로 지정한 모듈을 활성화시키는 명령입니다.

이 명령은 /etc/apache2/mods-available 디렉터리에 존재하는 모듈들 중 지정한 모듈 관련 파일에 대한 심볼릭 링크를  /etc/apache2/mods-enabled 디렉터리에 생성하는 것입니다.

a2dismod
활성화된 모듈을 비활성화하고자 한다면  'a2dismod 모듈명' 명령을 사용하시면 됩니다.

root@linux:/# systemctl restart apache2

root@linux:/# cd /etc/apache2/sites-available

파일확인

root@linux:/etc/apache2/sites-available# ls

virtualhost.comf 파일을 아래와같이 수정해주자

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerName virtualhost.co.kr
        ServerAlias virtualhost.co.kr
        DocumentRoot /var/www/virtualhost
        DirectoryIndex index.php
        ErrorLog $/ssl-t_error.log
        CustomLog $/ssl-nt_access.log combined

        LogLevel info ssl:warn

        #Include conf-available/serve-cgi-bin.conf

        SSLEngine on

        SSLCertificateFile /etc/ssl/ssc/virtualhost.co.kr.key.crt
        SSLCertificateKeyFile /etc/ssl/ssc/virtualhost.co.kr.key

        #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>

        # BrowserMatch "MSIE [2-6]" \
        #        nokeepalive ssl-unclean-shutdown \
        #        downgrade-1.0 force-response-1.0

    </VirtualHost>
</IfModule>

 

구문검사

root@linux:/# apache2ctl configtest

오류를 찾아서 수정해준다

보통 에러는 찬찬히 읽어보면 워가 잘못된건지 알려준다

경로가 잘못되었다

        ErrorLog /var/log/apache2/ssl-virtualhost_error.log
        CustomLog /var/log/apache2/ssl-virtualhost_access.log combined

요렇게 수정해주자

root@linux:/# sudo systemctl reload apache2

라고했는데..

여기까지는 자체인증서네??

장난치나..ㅡㅡ;

 

 

나는 Encrypt 를 이용해서 하고싶다고~!

위에서 만든 자체 인증서는 바로 칼 삭.

 

다시

root@linux:/etc# cd /etc/apache2/sites-available/

root@linux:/etc/apache2/sites-available# ll

 

root@linux:/etc/apache2/sites-available# cp default-ssl.conf mydomin.conf

root@linux:/# ln -s /etc/apache2/sites-available/mydomin.co.kr /etc/apache2/sites-enabled/

Certbot 설치하기

root@linux:/# apt install certbot python3-certbot-apache -y

root@linux:/# vi /etc/apache2/sites-available/mydomin.co.kr

5번라인 DocumentRoot /var/www/html -> DocumentRoot /var/www/mydomin

그리고 아래 두줄을 6,7번라인이나 아무곳이나 추가해준다

ServerName mydomin.co.kr
ServerAlias mydomin.co.kr

 

그리고저장

 

 

root@linux:/etc/apache2/sites-available# apache2ctl configtest

 

SSL인증서 발급받기

아래 내용에 #옆에 한글로 적은건 그냥 설명이니까 그런갑다 하면된다.실제로 명령어를 적는건아니다.

root@linux:/etc/apache2/sites-available# certbot --apache
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): mydomin.mydomin@gmail.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: a    #뭔진몰라도 동의할꺼지?

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: 

y    #그래 뭔지몰라도 yes


No names were found in your configuration files. Please enter in your domain
name(s) (comma and/or space separated)  (Enter 'c' to cancel): mydomin.co.kr  #인증받을 도메인을 적어주자
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for 
Enabled Apache rewrite module
Waiting for verification...
Cleaning up challenges
Created an SSL vhost at /etc/apache2/sites-available/000-default-le-ssl.conf
Deploying Certificate to VirtualHost /etc/apache2/sites-available/000-default-le-ssl.conf
Enabling available site: /etc/apache2/sites-available/000-default-le-ssl.conf

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2   #http로 들어오면 자동으로 https 로 쏴줄끼여? 그럴거면 2번~
Enabled Apache rewrite module
Redirecting vhost in /etc/apache2/sites-enabled/000-default.conf to ssl vhost in /etc/apache2/sites-available/000-default-le-ssl.conf

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://mydomin.co.kr

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=mydomin.co.kr
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live//fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/privkey.pem
   Your cert will expire on 2022-05-06. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

root@linux:/etc/apache2/sites-available#

 

위와깉이 뜬다면 완성~!

자..이제.../etc/apache2/sites-available/에 들어가보면

이렇게 ssl 용 컨피그 파일이 있는걸 확인할 수 있다.

 

기본적으로 apache2용 certbot 패키지는 하루에2번씩 인증서 기간을 체크해서 30일 이하가 남았을경우 자동으로 갱신을 도와주기 때문에 참고

 

갱신 테스트 명령어는
root@linux:/# certbot renew --dry-run

나중에 크론탭에 넣어두면 편하다.

 

여기까지했으면..이제 서버셋팅은끝났으니

mysql 관리를 위해서 phpmyadmin 을 설치하러 가자

다음글을보면된다

 

 

 

 

 

반응형