Apache: VirtualHost

Byphunsanit

Apache: VirtualHost

ถ้าต้องการเพิ่มเว็บเข้าไปใน host โดยที่แยกคนละ site คนละโดแมนออกจากกันเพื่อความสะดวกในการดูแล

  1. เพิ่ม directory สำหรับเก็บข้อมูลก่อน
    sudo mkdir -p /Users/Shared/www/example.com/published
  2. ตั้งสิทธิให้ apache เข้าไปวิ่งเล่นเขียนอ่านได้
    cd /Users/Shared/www/example.com/published
    sudo chown -R www-data:www-data *;
    sudo find . -type d -exec chmod 755 {} \;
    sudo find . -type f -exec chmod 644 {} \;
  3. สร้างไฟล์ configuration แยกออกมาจากตัวเดิม
    sudo nano /etc/apache2/sites-available/example.com.conf
  4. พิมพ์ตามตัวอย่าง
    <VirtualHost *:443 *:80>
        <Directory "/Users/Shared/www/example.com/published">
            #Access control in Apache 2.2:
            #Allow from all
            #Order allow,deny
            #Access control in Apache 2.4:
            Require all granted
    
            AllowOverride All
            Options FollowSymLinks MultiViews
        </Directory>
    
        DefaultLanguage th_TH
        DocumentRoot /usr/share/www/example.com/published
        #log files
        CustomLog ${APACHE_LOG_DIR}/example.com.access.log "combined"
        ErrorLog ${APACHE_LOG_DIR}/example.com.error.log
    
        RewriteEngine on
        #rewrite to https
        RewriteCond %{SERVER_NAME} =www.example.com
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    
        #security
        php_admin_value open_basedir "/usr/share/www/example.com/published"
    
        #server
        ServerAdmin [email protected]
        ServerAlias www.example.com
        ServerName example.com
    </VirtualHost>
    
    • line 1 <VirtualHost *:443 *:80 ถ้าใส่ไว้ port เดียวอย่าลืมเช็คคอนฟิกของ SSL ด้วย บางระบบจะเขียนไว้ในไฟล์ต่างกัน เช่น เพิ่ม suffix -le-ssl ใน Let’s Encrypt
    • best practice ที่ดีคือ ถ้า http และ https ต่างกันมาก ควรแยกคอนฟิกเกอเรชั่นแยกกัน
    • line 3 ใน Access control เลือกให้ตรงกับ apache version ที่ใช้ ถ้าไม่ใช้ให้ลบออก หรือใส่ # ไว้ด้านหน้า
    • line 2, 14 ตำแหน่งในการ run PHP และให้ user เรียกดูไฟล์ css, js, รูปภาพได้
    • line 18 เป็นส่วนที่กำหนดให้ run PHP ในนี้เท่านั้น
    • ส่วนที่เป็น ServerAlias และ ServerName จะเป็นตัวที่ให้ apache เลือกว่าจะแสดงผลให้ URL อะไร เช่น ในการทดสอบอาจจะเปลี่ยนเป็น www.pitt.plusmagi.internal และ pitt.plusmagi.internal
  5. ดูว่า load config โดย
    apachectl -S
    ควรจะเห็น part /etc/apache2/sites-available/example.com.con.conf ในผลลัพธ์
  6. เทส config โดย
    sudo apache2ctl configtest
  7. เปิดใช้งาน configuration
    sudo a2ensite example.com.conf
  8. รีสตาร์ apache
    sudo systemctl restart apache2

ทดลองใส่ไฟล์เข้าไปใน /Users/Shared/www/example.com/published แล้วเรียก url ที่ใส่เพิ่มเข้าไปดูว่าสามารถเรียกได้รึเปล่า

อ่านเพิ่มเติม

About the author

phunsanit administrator

Leave a Reply