Redirect with . htaccess if url contains string

Asked

Viewed 289 times

0

I am working on an application using Angular4 and PHP, for the Angular URL to work, I need to use a certain configuration in .htaccess to direct to the index.html, thus:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /
    RewriteRule ^index.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

So far, everything works as it should, I can access and give refresh on any page without any problem. However, I also want to use the route system on PHP, therefore, I need another type of configuration to direct calls to the index.php, which is in another folder. The project directory is more or less like this:

raiz
│ index.html
│ vendor.bundle.js    
| [outros arquivos .js]  
│
└─api
│  │ index.php
│  │ init.php
│  │
│  └─vendor
└─assets
└─[outros arquivos]

And this is the configuration to make the route system PHP work:

<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . api/index.php [L]
</IfModule>

The problem is that I can’t make both work at the same time. Or it works the route in Angular or in PHP, but not the two together.

The routes in PHP need to be directed to the archive /api/index.php only when I call some url that contains the string /api/'alguma-coisa', I mean, you’ll always have the prefix /api/.

How to fix this problem and use both route systems?

...or, if there is another solution, I can use it quietly as long as it achieves the ultimate goal.

2 answers

1


I don’t possess very advanced knowledge in .htaccess, but I managed to resolve the issue by changing only 2 lines. I removed RewriteRule ^index.html$ - [L] and I moved this part RewriteBase / to the top. With a final code like this:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    RewriteCond %{REQUEST_URI} api 
    RewriteRule . api/index.php [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

But I will leave the question still open if someone has a better or more educational answer on the subject.

1

Nice that you solved, but there is another way that would put another . htaccess inside an "api/" folder, and point the route to it, example:

Imagine you have a folder: /raiz/public/ Then you create a folder: /raiz/api/

Puts the .htaccess with the following inscription:

RewriteEngine On
RewriteRule ^(.*)$  /raiz/public/$1 

The following example would call your public folder every time you access the subdirectory api/{aqui ele iria reescrever tudo que chegasse}:

/api/alguma-coisa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.