在搭建网站时,你是否希望将丑陋的动态链接(如 example.com/index.php?id=123)变成美观、SEO友好的静态链接(如 example.com/article/123)?这就需要用到URL重写技术。本文将详细讲解如何在Ubuntu系统中为常见的Web服务器(Apache 和 Nginx)配置URL重写规则,即使你是零基础的小白,也能轻松上手!
URL重写(URL Rewriting)是一种将用户请求的URL地址在服务器内部转换为另一个真实路径的技术。它不仅能让网址更简洁、易读,还能提升搜索引擎优化(SEO)效果,增强网站安全性。
在开始之前,请确保你已满足以下条件:
如果你使用的是 Apache,需要启用 mod_rewrite 模块。
在终端中执行以下命令:
sudo a2enmod rewritesudo systemctl restart apache2 你可以选择在站点的虚拟主机配置文件中添加规则,也可以使用 .htaccess 文件(需确保 AllowOverride 设置为 All)。
编辑你的站点配置文件(例如 /etc/apache2/sites-available/000-default.conf),在 <Directory> 块中加入:
<Directory /var/www/html> Options Indexes FollowSymLinks AllowOverride All Require all granted</Directory> 然后重启 Apache:
sudo systemctl restart apache2 在网站根目录(如 /var/www/html)下创建 .htaccess 文件:
sudo nano /var/www/html/.htaccess 添加如下基本重写规则(以将 /article/123 映射到 article.php?id=123 为例):
RewriteEngine OnRewriteRule ^article/([0-9]+)/?$ article.php?id=$1 [L] 保存并退出。现在访问 http://your-domain/article/123 就能正常加载内容了!
如果你使用的是 Nginx,URL 重写通过 rewrite 指令实现,无需额外模块。
通常位于 /etc/nginx/sites-available/ 目录下。例如:
sudo nano /etc/nginx/sites-available/default 在 server 块中添加如下规则:
server { listen 80; server_name your-domain.com; root /var/www/html; index index.html index.php; location /article/ { rewrite ^/article/([0-9]+)/?$ /article.php?id=$1 last; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; }} sudo nginx -tsudo systemctl reload nginx 配置成功后,同样可以访问 http://your-domain/article/123。
/var/log/apache2/error.log 或 Nginx 的 /var/log/nginx/error.log 日志。AllowOverride All 已设置。通过本文,你已经学会了在 Ubuntu 系统中为 Apache 和 Nginx 配置 URL重写规则。无论你是想提升网站 SEO 效果,还是让 URL 更加用户友好,这些技巧都非常实用。记住关键词:Ubuntu URL重写、Apache mod_rewrite、Nginx URL重写规则 和 Linux服务器URL美化,它们将帮助你在未来快速检索相关知识。
动手试试吧!如有疑问,欢迎在评论区留言交流。
本文由主机测评网于2025-12-18发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025129536.html