1

i've used htaccess for something like this

domain.com/bacaberita.php -> domain.com/baca-berita

and i need passing get varible like this

domain.com/bacaberita.php?id=xy0001

how to hide the variable id so the url going to be domain.com/baca-berita/xyz0001

i'm using htacces code

RewriteRule ^baca-berita bacaberita.php
RewriteRule ^baca-berita/(.*) bacaberita.php?id=$1

but it throws id was empty

i've try this code only

RewriteRule ^baca-berita/(.*) bacaberita.php?id=$1

it work but the css and all images file can not called in the page

1
  • Your first rule matches baca-berita/xyz0001 already, so it gets rewritten to bacaberita.php. You need to anchor your pattern not only at the beginning, but at the end as well, if you want to avoid that. ^baca-berita$, or ^baca-berita/?$ if you want to allow an optional trailing slash. And in general, you should keep your RewriteRules ordered from more specific to less specific. Commented Mar 10, 2020 at 7:45

1 Answer 1

1

You want to put some rewrite conditions before your rewrite rules to ignore those asset files.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !/assets
RewriteRule ^baca-berita/(.*) bacaberita.php?id=$1

This tells the server to check that the files or directories exist, then to ignore them in the rewrite if in those directories.


Update

You also want to make sure your assets inside bacaberita.php are linked from the root of the site and not relatively. You can do this by ensuring you always use a / at the beginning:

<!-- incorrect: looks for styles in domain.com/bacaberita/assets -->
<link rel="stylesheet" type="text/css" href="assets/css/styles.css">

<!-- correct: looks for styles in domain.com/assets -->
<link rel="stylesheet" type="text/css" href="/assets/css/styles.css">
Sign up to request clarification or add additional context in comments.

4 Comments

my assets folder structure is like this assets -> css, images i tried this still won't work RewriteCond %{REQUEST_URI} !/assets
Sorry, I missed two important conditions (checking the files/dirs exist). I updated the answer.
all of my styling file like bootstrap images css js was inside the assets folder i've tried your tips the page still unstyled and the problem only occur this baca-berita page
I was able to reproduce your problem and I updated my answer above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.