ubuntu apache2伺服器配置

來源:互聯網
上載者:User

標籤:

把django開發好的項目部署到apache2伺服器。 記錄我的配置過程。

apache,django,mod_wsgi,python版本如下。不同版本大同小異。

ii  apache2                           2.2.22-1ubuntu1.6                   Apache HTTP Server metapackageii  python-django                     1.3.1-4ubuntu1.11                   High-level Python web development frameworkii  libapache2-mod-wsgi               3.3-4ubuntu0.1                      Python WSGI adapter module for Apacheii  python                            2.7.3-0ubuntu2.2                    interactive high-level object-oriented language (default version)
一、apache2配置說明

ubuntu 用apt-get install apache2安裝apache2後,設定檔都在/et/apache2目錄下。

基本原理

apache2在啟動的時候自動讀取/etc/apache2/apache2.conf檔案的配置資訊,不同的配置項按功能分布在不同的檔案中,然後被Include包含到apache2.conf這個主設定檔中,方便管理。就是說事實上apache2主設定檔只有一個,即apache2.conf,其他的都是被include進來的。可以把所有的配置都放在apache2.conf或者任何一個設定檔中,但是劃分到不同檔案會讓我們管理起來方便很多,何樂而不為?

1、apache2.conf設定檔

該檔案是apache的主設定檔,包括三個層級的配置。

  • 控制apache伺服器執行過程的全域配置。
  • 定義主服務或者預設伺服器的參數的配置,這些配置會響應virtual host不處理的請求。這類配置也為所有的virtual hosts配置提供預設值。
  • virtual hosts相關的配置,使得同一個apache服務進程處理向不同IP地址或者主機名稱發送的請求。
### Section 1: Global Environment#ServerRoot:apache伺服器根目錄。主設定檔,日誌都在該目錄。#注意路徑結束時不要加斜杠,預設是/etc/apache2#ServerRoot "/etc/apache2"LockFile ${APACHE_LOCK_DIR}/accept.lock#apache服務啟動時在該檔案記錄進程ID號# This needs to be set in /etc/apache2/envvarsPidFile ${APACHE_PID_FILE}#連線逾時,單位秒Timeout 300#是否允許持久串連KeepAlive On#持久串連時最大請求數MaxKeepAliveRequests 100KeepAliveTimeout 5# prefork MPM<IfModule mpm_prefork_module>    StartServers          5    MinSpareServers       5    MaxSpareServers      10    MaxClients          150    MaxRequestsPerChild   0</IfModule># worker MPM<IfModule mpm_worker_module>    StartServers        10    ServerLimit         100    MinSpareThreads     50    MaxSpareThreads     200    ThreadsPerChild     64    MaxClients          6400    MaxRequestsPerChild   0</IfModule># event MPM<IfModule mpm_event_module>    StartServers          2    MinSpareThreads      25    MaxSpareThreads      75    ThreadLimit          64    ThreadsPerChild      25    MaxClients          150    MaxRequestsPerChild   0</IfModule># These need to be set in /etc/apache2/envvarsUser ${APACHE_RUN_USER}Group ${APACHE_RUN_GROUP}#apache服務啟動後在每個目錄中尋找尾碼是.htaccess的檔案,這些檔案作為附加的配置AccessFileName .htaccess#下面幾行防止.htaccess和.htpassword檔案被web用戶端訪問<Files ~ "^\.ht">    Order allow,deny    Deny from all    Satisfy all</Files>#DefaultType是瀏覽器訪問的MIME類型,設定為None,讓瀏覽器自行解析DefaultType None# HostnameLookups: Log the names of clients or just their IP addresses# e.g., www.apache.org (on) or 204.62.129.132 (off).HostnameLookups Off#錯誤記錄檔檔案目錄,預設是配置在此,可在<VirtualHost>中重載#記錄檔取名時以‘/‘開頭會造成衝突,不以‘/‘開頭,會預設加上伺服器根目錄首碼#比如"foo.log"會被加上ServerRoor目錄"/etc/apache2"變成"/etc/apache2/foo.log"ErrorLog ${APACHE_LOG_DIR}/error.log#Log日誌記錄哪些資訊,取值可以是: debug, info, notice, warn, error, crit,alert, emerg.LogLevel warn#匯入模組設定檔Include mods-enabled/*.loadInclude mods-enabled/*.conf#匯入所有使用者設定檔Include httpd.conf#匯入連接埠監聽設定檔Include ports.conf# The following directives define some format nicknames for use with# a CustomLog directive (see below).# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i#LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combinedLogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combinedLogFormat "%h %l %u %t \"%r\" %>s %O" commonLogFormat "%{Referer}i -> %U" refererLogFormat "%{User-agent}i" agent#匯入通用配置目錄Include conf.d/#匯入虛擬機器主機的配置Include sites-enabled/
View Code2、apache2其他設定檔和子目錄
#2.2.22版本的apache2配置目錄
[email protected]:/etc/apache2# tree -L 1.├── apache2.conf 全域配置├── apache.pem├── conf.d 一般性設定檔存放地├── envvars 環境變數├── httpd.conf├── magic├── mods-available 已安裝的模組├── mods-enabled 已啟用的模組├── ports.conf httpd服務連接埠資訊├── sites-available 可用網站資訊├── sites-enabled 已經啟用的網站資訊,當中的檔案是到/etc/apache2/sites-available/ 檔案的軟串連。

2.4.7版本的apache2設定檔目錄如下

字元集

配置apache網站字元編碼, /etc/apache2/conf.d/charset檔案取消注釋#AddDefaultCharset UTF-8

ports.conf

修改連接埠的話,/etc/apache2/ports.conf檔案中修改NameVirtualHost *:80 改為NameVirtualHost x.x.x.x:80

sites-available和sites-enabled目錄

sites-available目錄是存放可用的內容,但不起作用,只有用ln 連到sites-enabled目錄才可以起作用。sites-enabled目錄存放真正起作用的設定檔,存放一些指向sites-available目錄的符號連結。所以apache上配置了多個虛擬機器主機,每個虛擬機器主機的配置都放在sites-available下,那麼對於虛擬機器主機的停用和啟用就非常方便。當sites-enabled下建立一個指向某個虛擬機器主機設定檔的串連時,就啟用了它。如果要關閉某個虛擬機器主機的話,只需要刪除相應的符號連結即可,不用去改設定檔。

mods-available和mods-enabled目錄

和上面說的sites-available、sites-enabled類似,這兩個目錄 是存放apache功能模組的設定檔和連結的。比如用apt-get install php5安裝了PHP模組後,在這兩個目錄裡就有了php5.load、php5.conf和指向這兩個檔案的連結。安裝mod-wsgi也一樣。這種目錄結構對於啟用、停用某個 Apache模組是非常方便的。

配置完apache伺服器後,重點就是要指定項目根目錄的位置,Ubuntu預設是/var/www。可以在/etc/apache2/sites-available目錄的default中看到

[email protected]:/etc/apache2/sites-available# cat default<VirtualHost *:80>        ServerAdmin [email protected]        DocumentRoot /var/www        <Directory />                Options FollowSymLinks                AllowOverride None        </Directory>        <Directory /var/www/>                Options Indexes FollowSymLinks MultiViews                AllowOverride None                Order allow,deny                allow from all        </Directory>        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/        <Directory "/usr/lib/cgi-bin">                AllowOverride None                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch                Order allow,deny                Allow from all        </Directory>        ErrorLog ${APACHE_LOG_DIR}/error.log        # Possible values include: debug, info, notice, warn, error, crit,        # alert, emerg.        LogLevel warn        CustomLog ${APACHE_LOG_DIR}/access.log combined    Alias /doc/ "/usr/share/doc/"    <Directory "/usr/share/doc/">        Options Indexes MultiViews FollowSymLinks        AllowOverride None        Order deny,allow        Deny from all        Allow from 127.0.0.0/255.0.0.0 ::1/128    </Directory></VirtualHost>
View Code

這個預設的配置在正式發布時不需要,所以就不要加到sites-enable目錄。需要訪問自己的項目,就需要配置虛擬機器主機。

二、配置虛擬機器主機

這裡配置的虛擬機器主機是同一台伺服器同時處理超過一個網域名稱。不同網域名稱訪問同一伺服器(即同一IP)的相同或不同目錄。

有效網站配置都在/etc/apache2/sites-available目錄。

1、<VirtualHost>文法

<VirtualHost>和</VirtualHost>是用來分裝一組僅作用於特定虛擬機器主機的配置。當伺服器接收到一個特定虛擬機器主機的文檔請求時,它會使用封裝在<VirtualHost>配置段的配置。

文法:

<VirtualHost addr[:連接埠] [addr[:連接埠]]...>

</VirtualHost>

addr可以是:

  • 虛擬機器主機的IP地址
  • 虛擬機器主機IP地址對應的完整網域名稱
  • 字元"*"
  • 字串"_default_",與基於IP的虛擬機器主機聯用以捕獲所有沒有匹配的IP地址
2、通過wsgi配置djagno項目的虛擬機器主機

第一步,在/etc/apache2/sites-available中建立xxx.org虛擬機器主機

[email protected]:/etc/apache2/sites-available# cat xxx.org<VirtualHost *:80>                                                                    
# 這裡要注意,目錄是工程目錄,根據實際情況修改,後面的django.wsgi檔案需要手動建立
WSGIScriptAlias
/ /var/www/stack/wsgi/django.wsgiAlias /site_media /var/www/stack/static_resourceServerName www.xxx.org
#Directory對根目錄限制
<Directory /var/www/stack/static_resource>    Options  None FollowSymLinks #followsymlinks表示是否允許使用符號連結,預設為禁用    AllowOverride None #標記禁止使用者對目錄設定檔(.htaccess進行修改)重載,普通網站不建議開啟    Order allow,deny #以allow優先處理,未明確說明允許的都拒絕    Allow from all #明確指出允許所有訪問</Directory><Directory /var/www/stack/wsgi>    #AuthType Basic      #AuthName "xxx"      #AuthUserFile /var/www/access      #Require valid-user     Order allow,deny    Allow from all</Directory>ErrorLog   /etc/apache2/xxx.org.error.logLogLevel warn</VirtualHost>

第二步,在/var/www/stack/wsgi目錄中建立一個django.wsgi。

[email protected]:/var/www/stack/wsgi# cat django.wsgi import osimport sysimport django.core.handlers.wsgifrom django.conf import settings# Add this file path to sys.path in order to import settingssys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), ‘../..‘))os.environ[‘DJANGO_SETTINGS_MODULE‘] = ‘stack.settings‘sys.stdout = sys.stderrSTACK_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))sys.path.append(STACK_PATH)DEBUG = Trueapplication = django.core.handlers.wsgi.WSGIHandler()

sys.path.insert()的參數是工程目錄的上級目錄,根據工程目錄情況修改。

os.environ[‘DJANGO_SETTINGS_MODULE‘]=‘stack.settings‘,這個stack.settings是工程目錄下的setting檔案,根據工程目錄名稱不同需要修改。

django.wsgi檔案名稱可以隨便取,但是一定要與虛擬機器主機中WSGIScriptAlias配置的名稱保持一致。

資源連結:mod_wsgi實現一些配置命令的詳細解釋

第三步,上一步配置好的內容只是“有效”虛擬機器主機,真正發揮效果的話得放到 /etc/apache2/sites-enabled 檔案夾下面。所以使用ln命令來建立一對關聯檔案:

ln -s /etc/apache2/sites-available/xxx.org /etc/apache2/sites-enabled/xxx.org

第四步,檢查文法,重啟web服務

謹慎起見,在重啟服務前先檢查文法:

sudo apache2ctl configtest

如果沒有錯誤,再重啟apache2

# /etc/init.d/apache2 restart

或者用service apache2 restart命令。現在就可以通過www.xxx.org來訪問django項目了。

3、配置wiki虛擬伺服器

【這裡wiki使用的是mediawiki,用php寫的,所以不用mod-wsgi】

第一步,在/etc/apache2/sites-available中建立mediawiki的虛擬機器主機

[email protected]:/etc/apache2/sites-available# cat wiki.xxx.org<VirtualHost *:80>                                                                                                                       Alias /wiki /var/lib/mediawikiAlias /index.php /var/lib/mediawiki/index.php
#網域名稱配置ServerName wiki.xxx.org
<Directory /var/lib/mediawiki/> Options FollowSymLinks AllowOverride None Order allow,deny Allow from all</Directory>#log檔案配置ErrorLog /etc/apache2/wiki.xxx.org.error.log LogLevel warn</VirtualHost>

第二步,上一步配置好的內容只是“有效”虛擬機器主機,真正發揮效果的話得放到 /etc/apache2/sites-enabled 檔案夾下面。所以使用ln命令來建立一對關聯檔案:

ln -s /etc/apache2/sites-available/wiki.xxx.org  /etc/apache2/sites-enabled/wiki.xxx.org

第三步,檢查文法,重啟web服務

謹慎起見,在重啟服務前先檢查文法:

sudo apache2ctl configtest

如果沒有錯誤,再重啟apache2

# /etc/init.d/apache2 restart

或者用service apache2 restart命令。現在就可以通過wiki.xxx.org/index.php來訪問wiki了。

資源連結:

apache虛擬機器主機文檔

apache虛擬機器主機配置

ubuntu apache2伺服器配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.