静态路由配置
本文最后更新于 2025-02-10,墨迹未干时,知识正鲜活。随着时间推移,文章部分内容可能需要重新着墨,请您谅解。Contact
静态路由配置
静态路由说人话就是把你服务器上的文件和资源链接到外部(一般就是公网)。其配置方式高度依赖于你所使用的 Web 服务器软件, 不同的服务器有不同的配置文件和语法,核心思想都是建立 URL 路径与服务器上文件之间的映射关系,下面举几个栗子。
Apache
AI的解释:Apache 是最流行的 Web 服务器之一,通常使用 .htaccess
文件(分布式配置文件)或主配置文件(通常是 httpd.conf
或 apache2.conf
)来配置静态路由。
-
.htaccess
文件-
优点:
- 无需重启 Apache 服务器即可生效(除非配置了不允许覆盖)。
- 方便对特定目录进行配置。
-
缺点:
- 会稍微降低性能(因为 Apache 需要在每个请求中检查
.htaccess
文件)。 - 如果配置不当,可能导致安全问题。
- 会稍微降低性能(因为 Apache 需要在每个请求中检查
-
示例:
# 开启 Rewrite 引擎 RewriteEngine On # 1. 基本的路径映射 # 将 /about 请求映射到 about.html 文件 RewriteRule ^about$ about.html [L] # 2. 将 /contact 请求映射到 contact.php 文件(即使是 .php 文件也可以作为静态资源提供) RewriteRule ^contact$ contact.php [L] # 3. 隐藏文件扩展名 # 将 /blog/my-post 请求映射到 /blog/my-post.html RewriteRule ^blog/([a-zA-Z0-9-]+)$ blog/$1.html [L] # 4. 将旧 URL 重定向到新 URL (301 永久重定向) RewriteRule ^old-page$ /new-page [R=301,L] # 5. 阻止访问特定文件或目录 RewriteRule ^secret\.txt$ - [F,L] # 禁止访问 secret.txt (返回 403 Forbidden) RewriteRule ^private/ - [F,L] # 禁止访问 private 目录及其内容 # 6. 如果请求的文件不存在,则显示 404 页面 ErrorDocument 404 /404.html # 7. 为特定文件类型设置缓存头(例如,缓存图片 1 个月) <FilesMatch "\.(jpg|jpeg|png|gif)$"> Header set Cache-Control "max-age=2592000, public" </FilesMatch> #8. 处理目录的默认页面 DirectoryIndex index.html index.php
-
注意事项:
- 确保 Apache 启用了
mod_rewrite
模块(通常默认启用)。 - 确保你的虚拟主机配置允许
.htaccess
文件覆盖 (AllowOverride All
或至少AllowOverride FileInfo
和AllowOverride Options
)。
- 确保 Apache 启用了
-
-
主配置文件 (httpd.conf 或 apache2.conf)
-
优点:
- 性能更好,因为配置只在服务器启动时加载一次。
- 更安全,因为配置集中在一个地方。
-
缺点:
- 修改后需要重启 Apache 服务器才能生效。
-
示例 (在
<VirtualHost>
块内):<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/example.com # 1. 启用 RewriteEngine (通常在全局配置中已经启用) # RewriteEngine On # 2. 基本的路径映射 (与 .htaccess 类似) RewriteRule ^about$ about.html [L] # 3. 定义 Alias (别名) - 将 /images 映射到 /var/www/images 目录 Alias /images /var/www/images <Directory /var/www/images> Require all granted # 允许访问 </Directory> # 4. 使用 <Location> 块进行更细粒度的控制 <Location /blog> # 仅对 /blog 路径下的请求应用以下规则 RewriteRule ^([a-zA-Z0-9-]+)$ $1.html [L] </Location> #5. 配置默认页面 DirectoryIndex index.html index.php # 6. 错误页面 ErrorDocument 404 /404.html </VirtualHost>
-
Nginx
AI的解释:Nginx 是一个高性能的 Web 服务器和反向代理服务器,通常使用 nginx.conf
文件或站点特定的配置文件(通常在 /etc/nginx/sites-available/
或 /etc/nginx/conf.d/
目录下)来配置静态路由。
-
站点配置文件示例:
server { listen 80; server_name example.com; root /var/www/example.com; # 网站根目录 index index.html index.htm; # 默认首页文件 # 1. 基本的路径映射 location /about { try_files $uri $uri/ /about.html; # 尝试按顺序查找: # 1. 请求的 URI 本身 ($uri) # 2. 请求的 URI 作为一个目录 ($uri/) # 3. 如果以上都不存在,则返回 /about.html } # 2. 隐藏文件扩展名 location /blog { try_files $uri $uri/ $uri.html =404; # 尝试查找 .html 文件,如果找不到则返回 404 } #2.1 另一种隐藏扩展名的方法 location ~ ^/([a-zA-Z0-9-/]+)$ { try_files $uri $uri/ /$1.html =404; } # 3. 将特定目录作为静态资源提供 location /static { # 不需要 try_files,Nginx 会自动处理 # 可以设置缓存头等 expires 30d; # 缓存 30 天 } # 4. 重定向 location /old-page { return 301 /new-page; # 301 永久重定向 } # 5. 阻止访问 location /secret.txt { deny all; # 禁止所有访问 } # 6. 错误页面 error_page 404 /404.html; # 7. 为特定文件类型设置缓存头 location ~* \.(jpg|jpeg|png|gif)$ { expires 30d; add_header Cache-Control "public"; } #8. 对请求路径进行正则匹配 location ~* ^/img/.*\.(jpg|jpeg|png|gif)$ { # 如果请求匹配此模式,则... expires 30d; add_header Cache-Control "public"; } }
-
try_files 指令的详细解释
try_files
是Nginx中用于处理静态路由的关键指令. 它的语法如下:
try_files file1 file2 ... uri;
或者
try_files file1 file2 ... =code;
file1
,file2
, ...: 依次尝试查找的文件或目录.uri
: 如果前面的文件或目录都不存在, 则内部重定向到这个uri
.=code
: 如果前面的文件或目录都不存在, 则返回指定的HTTP状态码(例如=404
).
$uri
和$uri/
是Nginx的内置变量:$uri
: 表示当前请求的URI(不包含查询字符串).$uri/
: 表示当前请求的URI, 并在末尾加上/
, 用于表示目录.
-
注意事项:
- 修改 Nginx 配置后,需要重新加载或重启 Nginx 才能生效(
sudo nginx -s reload
或sudo systemctl restart nginx
)。 - Nginx的配置语法比Apache更严格, 一定要注意空格和分号.
- 修改 Nginx 配置后,需要重新加载或重启 Nginx 才能生效(
-
Node.js (Express)
使用 Node.js 和 Express 框架,可以非常灵活地配置静态路由。
const express = require('express');
const path = require('path'); // 引入 path 模块
const app = express();
const port = 3000;
// 1. 使用 express.static 中间件提供静态文件服务
// 'public' 目录下的所有文件都将可以通过 / 访问
app.use(express.static('public'));
// 例如:
// - public/index.html -> http://localhost:3000/index.html
// - public/css/style.css -> http://localhost:3000/css/style.css
// - public/images/logo.png -> http://localhost:3000/images/logo.png
// 2. 可以指定虚拟路径前缀
app.use('/static', express.static('public'));
// 现在,'public' 目录下的文件需要通过 /static/ 访问
// - public/index.html -> http://localhost:3000/static/index.html
// 3. 手动定义特定的静态路由
app.get('/about', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'about.html'));
// path.join 用于安全地拼接路径
});
app.get('/contact', (req,res)=>{
res.sendFile(path.join(__dirname, 'views', 'contact.html'))
})
// 4. 处理 404 错误 (放在所有路由的最后)
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
- path 模块的解释
path.join()
: 用于将多个路径片段安全地拼接成一个完整的路径. 它可以处理不同操作系统下的路径分隔符(例如, Windows上是\
, Linux和macOS上是/
), 避免手动拼接可能出现的错误.__dirname
: Node.js中的一个全局变量, 表示当前执行脚本所在的目录的绝对路径.
Python (Flask)
Flask 是一个轻量级的 Python Web 框架。
from flask import Flask, send_from_directory, render_template
app = Flask(__name__) # 默认情况下,Flask 会在 'static' 文件夹中查找静态文件
# 1. 默认的静态文件路由 (static 文件夹)
# - static/style.css -> /static/style.css
# - static/images/logo.png -> /static/images/logo.png
# 2. 自定义静态文件夹
app = Flask(__name__, static_folder='assets', static_url_path='/public')
# - assets/script.js -> /public/script.js
# 3. 手动定义静态路由
@app.route('/')
def index():
return send_from_directory('static', 'index.html')
@app.route('/about')
def about():
return send_from_directory('static', 'about.html')
@app.route('/blog/<filename>') # 也可以带参数,但这里是静态路由,所以参数通常无意义
def blog_post(filename):
return send_from_directory('blog', filename + '.html')
#4. 使用render_template 渲染html模板
@app.route('/contact')
def contact_page():
return render_template('contact.html') #在templates文件夹中寻找
# 5. 处理 404 错误 (Flask >= 2.0)
@app.errorhandler(404)
def page_not_found(error):
return send_from_directory('static', '404.html'), 404
# return render_template('404.html'), 404 #也可以渲染模板
if __name__ == '__main__':
app.run(debug=True) # 开启调试模式,修改代码后自动重启
- Flask中的
static_folder
和static_url_path
static_folder
: 指定静态文件所在的文件夹名称(默认为'static'
).static_url_path
: 指定静态文件的URL前缀(默认为'/static'
). 可以修改它来改变静态文件的访问路径.
send_from_directory()
函数
Flask 提供的便捷函数,用于安全地发送指定目录下的文件。它会自动处理文件路径、MIME 类型等,避免安全漏洞。render_template()
函数
Flask提供的模板渲染函数,主要用于动态生成HTML,但是也可以渲染不包含动态数据的静态HTML。默认在templates
文件夹中寻找模板文件。