Search code examples
apache.htaccessmod-rewrite

Execute PHP script without Redirect


I have below Rewrite rule in .htaccess:

# /m/yyy rule
RewriteRule ^m/([\w-]+)/?$ accounts/$1/index.php [L,NC]
# /m/yyy/abc rule
RewriteRule ^m/([\w-]+)/([\w-]+)$ accounts/$1/$2.php [L,NC]
# /m/yyy/abc/ rule
RewriteRule ^m/([\w-]+)/([\w-]+)/$ accounts/$1/$2/index.php [L,NC]

I want to execute the PHP script view.php if the URL is https://example.com/m/mya/view.php, I expect accounts/mya/view.php to be executed.

Please advise how I can do.


Solution

  • I assume your existing rules are being used for other purposes, since none of them will match the stated URL.

    To internally rewrite the request /m/mya/view.php to /accounts/mya/view.php (as stated) then you would add the following before (or after) your existing rules:

    RewriteRule ^m/(mya/view\.php)$ accounts/$1 [L]
    

    To make this more generic and rewrite the request /m/<file> to /accounts/<file>, but only if /accounts/<file> exists then you can do something like the following instead before (or after) your existing rules:

    RewriteCond %{DOCUMENT_ROOT}/accounts/$1 -f
    RewriteRule ^m/([\w/-]+\.\w{2,5})$ accounts/$1 [L]
    

    UPDATE: The regex part \.\w{2,5} matches, what looks-like, a file extension. ie. a dot followed by between 2 and 5 word characters. If you are only matching .php files then you can change this to \.php to hardcode the .php extension. Use a regex testing tool such as regex101.com to test this and get a detailed explanation of the regex (this is not unique to Apache - Apache uses the same regex engine as PHP and other languages, ie. PCRE).

    The preceding RewriteCond (condition) directive then checks that this file exists at the intended destination before actually rewriting the request. Without this, the request is rewritten unconditionally, regardless of whether the target file exists or not. eg. /m/abc/xyz/does-not-exist.php would be internally rewritten to /accounts/abc/xyz/does-not-exist.php which then triggers a 404 later (potentially exposing the accounts subdirectory - depending on how you are handling your 404s).

    The order of these rules in relation to your existing rules as posted does not matter since the regex (RewriteRule patterns) do not conflict when making a request for a file (that contains a dot before the file extension).