skip to Main Content

I am trying to get the last directory name in a URL and send to a subfolder index.php as a parameter.

e.g.

mydomain.com/mysubfolder/hi
to
mydomain.com/mysubfolder/?p=hi

Next code in the .htaccess file do the redirect to the index.php without change the URL but the param is not sent.

RewriteEngine on
RewriteRule ^([^/]+)/?$ index.php?p=$1 [L] 

Note: The .htaccess is in "mysubfolder" not in the root.

I was reading others threads but none works.

Any idea why and how to solved it? Thanks

EDIT:

The problem is that I am trying to get the params with Javascript in the index.php file:

//Get URL Params
const queryString = window.location.search
const urlParams = new URLSearchParams(queryString)
const URL_p = urlParams.get('p')

I can´t understand why JS doesn’t catch the .htaccess parameters ($1 $2 etc..) but yes is geting parameters from {QUERY_STRING} .htaccess

It works correctly if I get the param with PHP Request:

<?php echo $_REQUEST[p] ; ?>

2

Answers


  1. Change your RegEx to match only second part of URL, not whole URL:

    RewriteEngine on
    RewriteRule ^[^/]+/(.*?)$ index.php?p=$1
    

    .htaccess tester

    Login or Signup to reply.
  2. To include subfolder, you would need regex with 2 variables,

    RewriteEngine on
    RewriteRule ^(.*?)/(.*?)$ $1/index.php?p=$2
    

    ^(.*?) – will contain your first immediate subfolder in variable $1

    /(.*?)$ – anything after the subfolder will be in variable $2

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