需要有关.htaccess url重写国家特定子目录网址的帮助

I am working on a project for making a website which contains country specific urls, to make it more targeted and separate.

Here what i want:

  1. open - domain.com and read this file index.php

  2. when open domain.com/us/ and read this file country.php ( /us/ it can be anything like /de/ /in/ /uk/ means its dynamically generated country code based on request.

  3. When open domain.com/us/free-free-free-ad1965.html ( its post on website with id 1965 from database, so its should read ad.php file.

  4. if open domain.com/xyz which does not exists it should give 404 error and read 404.php file same applies to domain.com/us/xyz

here is my current htaccess code:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
RewriteRule ^(.*)/ country.php?countrycode=$1 [NC]
RewriteRule ^(.*)/(.*)-ad(.*).html ad.php?countrycode=$1&post=$2&id=$3 [NC]
RewriteRule ^maintenance\.html$  maintenance.php [NC,L]
RewriteRule ^submit\.html$  submit.php [NC,L]
RewriteRule ^privacy\.html$  privacy.php [NC,L]
RewriteRule ^terms\.html$  terms.php [NC,L]
RewriteRule ^contact\.html$  contact.php [NC,L]

ErrorDocument 400 /404.php
ErrorDocument 401 /404.php
ErrorDocument 403 /404.php
ErrorDocument 404 /404.php
ErrorDocument 500 /404.php

after applying this htaccess option 1 works fine everytime and option 2 &3 & 4 is conflicting with each others. The all four options are seperate and should have to work with each other.

Please help me how can i do this?

How more specific the rule how further up it should be.

You should change the order.

rewriteRule ^(.)/(.)-ad(.*).html ad.php?countrycode=$1&post=$2&id=$3 [NC] Should probably be more up

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain.com [NC]
RewriteRule ^(.*)/(.*)-ad(.*).html ad.php?countrycode=$1&post=$2&id=$3 [NC]
RewriteRule ^(.*)/$ country.php?countrycode=$1 [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]


RewriteRule ^maintenance\.html$  maintenance.php [NC,L]
RewriteRule ^submit\.html$  submit.php [NC,L]
RewriteRule ^privacy\.html$  privacy.php [NC,L]
RewriteRule ^terms\.html$  terms.php [NC,L]
RewriteRule ^contact\.html$  contact.php [NC,L]

ErrorDocument 400 /404.php
ErrorDocument 401 /404.php
ErrorDocument 403 /404.php
ErrorDocument 404 /404.php
ErrorDocument 500 /404.php