.htaccess mod_rewrite subdirectory to URL parameter

后端 未结 3 670
日久生厌
日久生厌 2021-01-07 03:22

I hope this was not asked over and over again before, but I didn\'t get further to an answer using google, w3schools and so on. So here is my question: I\'m writing a script

相关标签:
3条回答
  • 2021-01-07 03:45

    Following what you ask, this is important not to do a redirect, but let the rewriterule modify internally the URL i.e. the RewriteRule should not end with [R,L] but rather [L] and maybe the "query string append" directive to keep what's after the ? so this should probably be [QSA,L].

    Now here's how I'd do to avoid rewriting static files: if it's not a file then (and only then) test it:

    # if it's not a file...
    RewriteCond %{SCRIPT_FILENAME} !-f
    # ... and it's a dir
    RewriteCond %{SCRIPT_FILENAME} -d
    # ... then rewrite it internally and stop further processing:
    RewriteRule projects/([^/]+)(/?)$ index.php?dir=$1 [QSA,L]
    

    And now two hints:

    Please try to use the RewriteLog directive: it helps you to track down such problems:

    # Trace:
    # (!) file gets big quickly, remove in prod environments:
    RewriteLog "/web/logs/mywebsite.rewrite.log"
    RewriteLogLevel 9
    RewriteEngine On
    

    My favorite tool to check for regexp:

    http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)

    0 讨论(0)
  • 2021-01-07 03:47

    Thanks for all the help so far! You guys are just awesome!

    I figured out that a symbiosis of both of your solutions works well for me:

    RewriteEngine on
    RewriteBase /projects
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} -d
    RewriteRule ^([^/]+)/?$ index.php?dir=$1 [QSA,L]
    

    Of course only without [R], this was my fault. (See my question edit for another question please).

    0 讨论(0)
  • 2021-01-07 03:53

    You need to add a RewriteBase /projects to the htaccess. That way the redirect will work properly.

    Edit:

    RewriteEngine on
    RewriteRule ^index.php - [L]
    RewriteRule ^([^/]+)/?$ index.php?dir=$1 [R,L]
    
    0 讨论(0)
提交回复
热议问题