這裡介紹在 Ubuntu Linux 中安裝與設定 LEMP 網頁伺服器的詳細步驟,以及安全性相關的注意事項。

LEMP(Linux、nginx、MySQL、PHP)是現在很熱門的網頁伺服器組合,它是將 LAMP 中的 Apache 以 nginx 取代,以提升伺服器的的負載能力,以下介紹在 Ubuntu Linux 中安裝 LEMP 的步驟。


這裡我是使用 Linode VPS 上面的 Ubuntu Linux 14.04 為測試環境,不過這些安裝方式應該適用於各種 Ubuntu Linux 版本,Ubuntu Linux 本身系統的設定請參考 Linode VPS 安裝 Ubuntu Linux 與基本安全性設定

nginx

使用 apt 安裝 nginx 套件:

apt-get install nginx

編輯 /etc/nginx/nginx.conf,調整 worker_processes 的數量:

worker_processes 1;

如果是 1 顆 CPU 的主機,就直接將 worker_processes 設定為 1 就好了,如果是多顆 CPU 的話,可以設定為 auto,詳細說明請參考 nginx 的文件

調整 events 設定,將 worker_connections 設定成適當的數值:

events {
  worker_connections 1024;
  use epoll;
  multi_accept on;
}

Linux 2.6 以後的核心可以使用 epoll 這種比較有效率的方式。

server_tokens 關掉,這樣網頁上就不會顯示 nginx 的版本資訊,減低被攻擊的機率:

http {
  # ...
  server_tokens off;
  # ...
}

對各種文字檔案啟用 gzip 壓縮,設定啟用壓縮的最小資料長度:

http {
  # ...

  gzip on;
  gzip_disable "msie6";

  # gzip_vary on;
  # gzip_proxied any;
  # gzip_comp_level 6;
  # gzip_buffers 16 8k;
  # gzip_http_version 1.1;
  gzip_min_length 1000;
  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

  # ...
}

關於 nginx 的 gzip 的壓縮設定,可以參考 nginx 的文件

接著是設定 virtual host,編輯 /etc/nginx/sites-available/default,不過這個部分就要根據自己的網站來調整了,下面這個是一個簡單的範例:

server {
  listen   80;

  root /usr/share/nginx/html;
  index index.php index.html index.htm;

  server_name gtwang.org;

  location / {
          try_files $uri $uri/ /index.html;
  }

  error_page 404 /404.html;

  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
        root /usr/share/nginx/html;
  }

  # pass the PHP scripts to FastCGI server listening on the php-fpm socket
  location ~ \.php$ {
          try_files $uri =404;
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          include fastcgi_params;
  }

  # Directives to send expires headers and turn off 404 error logging.
  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 7d;
    log_not_found off;
  }
}

最後重新啟動 nginx 服務:

sudo service nginx start