You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用.htaccess在PHP根目录重写URL:转换指定动态URL为伪静态

How to Rewrite Dynamic URL to Pretty Static URL in PHP via .htaccess

Hey there, let's get this URL rewrite sorted for your PHP project. You want to turn localhost/test/view/admin/process.php?action=dashboard into localhost/test/general/dashboard/—here's a straightforward solution using the .htaccess file in your test root folder.

Step 1: Ensure mod_rewrite is enabled

  • If you're using Apache, first confirm the mod_rewrite module is active. Most hosting providers have this enabled by default, but for local environments (like XAMPP/WAMP), you'll need to uncomment LoadModule rewrite_module modules/mod_rewrite.so in your Apache config file and restart the server.

Step 2: Create/Edit your .htaccess file

Drop these rules into the .htaccess file located directly in your test root directory:

# Enable URL rewriting engine
RewriteEngine On

# Set base path for rewrite rules
RewriteBase /test/

# Rewrite pretty URL to dynamic backend URL
RewriteRule ^general/([^/]+)/?$ view/admin/process.php?action=$1 [L,QSA]

Let's break down the key rule

  • RewriteEngine On: Mandatory to activate the URL rewriting functionality.
  • RewriteBase /test/: Ensures all rewrite rules target your test root directory correctly, avoiding path-related issues.
  • RewriteRule ^general/([^/]+)/?$ view/admin/process.php?action=$1 [L,QSA]:
    • ^general/([^/]+)/?$: This pattern matches your desired pretty URL.
      • ^ marks the start of the URL path.
      • general/ explicitly matches your specified module name.
      • ([^/]+) captures the page name (like dashboard) as a reusable variable.
      • /?$ allows an optional trailing slash, so both localhost/test/general/dashboard and localhost/test/general/dashboard/ will work.
    • view/admin/process.php?action=$1: Maps the pretty URL to your actual dynamic script, where $1 gets replaced with the captured page name.
    • [L,QSA]: Flags to control behavior—L stops processing further rules if this one matches, and QSA ensures any extra query parameters (if added later) are appended to the dynamic URL.

Quick checks to avoid issues

  • File permissions: Make sure your .htaccess file has permissions set to 644 so Apache can read it.
  • Test thoroughly: Clear your browser cache and test both the pretty URL and original dynamic URL to confirm they load the same content.
  • Rule conflicts: If you have existing rewrite rules, ensure these new ones don't clash—adjust the order of rules if needed.

内容的提问来源于stack exchange,提问作者Moorthi R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:36:04