skip to Main Content

Currently I have a “public” folder being root directory where all my frontend code goes.

But since my public folder contains both the website content and app content, I would like to split it more up.
So my idea was:

.htaccess (rewriting public url)
src (php backend code)
public/
  web/
    index.php
  app/
    account.php

So my problem is, I can easily go to the pages like this:
http://example.com/web/index.php
http://example.com/app/account.php

but I would like to remove “web” and “app” from the URL’s…
http://example.com/index.php
http://example.com/account.php

How can I do that using .htaccess? I’m running apache 2.4.

EDIT
An example of what I’ve tried:

RewriteEngine On
RewriteCond %{REQUEST_URI} !app/
RewriteRule (.*) /app/$1
RewriteCond %{REQUEST_URI} !web/
RewriteRule (.*) /web/$1

2

Answers


  1. Chosen as BEST ANSWER

    I've tried so many different things now, but I finally figured it out.

    RewriteEngine on
    RewriteBase /
    # Rewrite every web request
    RewriteCond         "%{DOCUMENT_ROOT}/web/%{REQUEST_URI}"  -f
    RewriteRule "^(.+)" "%{DOCUMENT_ROOT}/web/$1"
    
    # Rewrite every app request
    RewriteCond         "%{DOCUMENT_ROOT}/app/%{REQUEST_URI}"  -f
    RewriteRule "^(.+)" "%{DOCUMENT_ROOT}/app/$1"
    
    # Remove .php extension
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^.]+)$ $1.php [NC,L]
    

    This works when having a setup:

    public/ (root folder)<br>
       web/ (contains website frontend)<br>
       app/ (contains app frontend)<br>
       .htaccess (contains the code above)
    

  2. Probably you need to tune up your requests. But a first approach is:

    First, make sure that you have mod rewrite enabled.
    Second, write the following in the .htaccess

    RewriteEngine On
    RewriteRule ^[/]?index.php$ /web/index.php [NS,NC,L]
    RewriteRule ^[/]?account.php$ /app/account.php [NS,NC,L]
    

    You will need to read the documentation to make other rules. You can read it here
    https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

    Also pay special attention on the flags. Read the documentation to set the ones that applies to your situation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search