温馨提示×

如何在Ubuntu上部署静态网站

小樊
41
2025-12-09 02:33:58
栏目: 云计算

在Ubuntu上部署静态网站可以通过多种方式实现,以下是一些常见的方法:

方法一:使用Apache HTTP服务器

  1. 安装Apache

    sudo apt update
    sudo apt install apache2
    
  2. 启用必要的模块

    sudo a2enmod rewrite
    sudo systemctl restart apache2
    
  3. 将静态网站文件复制到Apache的默认文档根目录

    sudo cp -r /path/to/your/static/site /var/www/html/
    
  4. 配置Apache(可选): 如果你需要自定义配置,可以编辑/etc/apache2/sites-available/000-default.conf文件,添加或修改以下内容:

    <VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    
  5. 重启Apache

    sudo systemctl restart apache2
    

方法二:使用Nginx服务器

  1. 安装Nginx

    sudo apt update
    sudo apt install nginx
    
  2. 将静态网站文件复制到Nginx的默认文档根目录

    sudo cp -r /path/to/your/static/site /var/www/html/
    
  3. 配置Nginx: 编辑/etc/nginx/sites-available/default文件,添加或修改以下内容:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
    
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
    
        server_name _;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    
  4. 重启Nginx

    sudo systemctl restart nginx
    

方法三:使用Node.js和Express

如果你更喜欢使用Node.js来部署静态网站,可以使用Express框架。

  1. 安装Node.js和npm

    curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
  2. 创建一个新的Node.js项目

    mkdir my-static-site
    cd my-static-site
    npm init -y
    
  3. 安装Express

    npm install express
    
  4. 创建一个简单的Express服务器: 创建一个server.js文件,添加以下内容:

    const express = require('express');
    const path = require('path');
    const app = express();
    const port = 3000;
    
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}/`);
    });
    
  5. 将静态网站文件移动到public目录

    mkdir public
    cp -r /path/to/your/static/site/* public/
    
  6. 启动服务器

    node server.js
    

现在,你可以通过访问http://localhost:3000来查看你的静态网站。

方法四:使用Docker

如果你熟悉Docker,可以使用Docker来部署静态网站。

  1. 安装Docker

    sudo apt update
    sudo apt install docker.io
    
  2. 创建一个Dockerfile: 在你的静态网站目录中创建一个Dockerfile,添加以下内容:

    FROM nginx:latest
    COPY . /usr/share/nginx/html
    
  3. 构建Docker镜像

    docker build -t my-static-site .
    
  4. 运行Docker容器

    docker run -d -p 80:80 --name my-static-site-container my-static-site
    

现在,你可以通过访问http://localhost来查看你的静态网站。

选择适合你的方法进行部署即可。

0